(no title)
greggman3 | 3 years ago
That sounds like a fundamental mis-understanding. Variables do not hold objects, they hold references to objects.
const foo = {};
let bar = foo;
foo and bar hold references to the same object. They do not hold the object themselves. foo's reference can not be changed. It's const. bar's reference can. But the object is independent of both variables.If you want the object itself to be unmodifiable there's Object.freeze.
const foo ...
makes foo const. If you wanted a shortcut for making the object constant (vs Object.freeze) it would be something like let foo = new const SomeObject()
This doesn't exist but it makes more sense than believing that `const foo` some how makes the object constant. It only makes foo constant (the reference).
captainmuon|3 years ago
So
This is what I actually want when I think "const". I don't really care that you can reuse a variable, or re-seat a value. What I care about is that I recieve an object and sometimes want to modify it, and sometimes I want to make sure it stays the same. Maybe somebody else holds a reference and I don't want to surprise them.(The inverse problem is when I have a function that takes something like a string or a number, and I want to change that from within the function. There is no way to pass a value type by reference. You have to encapsulate the value in an object and pass that. It would be cool if you could say something like `function double(ref x) { &x = x*2; }`.)
greggman3|3 years ago
It could be worse. You could be in python that has no const whatsoever :P
I also agree pass by reference is useful. JavaScript only has pass by value, similar to python.
xtracto|3 years ago
https://www.typescriptlang.org/docs/handbook/utility-types.h...