> That brings me to something I really want in JS, actual unmutable values. If you use `const x = new SomeClass()`, you cannot reassign it, but you can change fields. The first time I encountered `const`, I thought it did the opposite. It would be cool if you could declare something (object, array) to be an immutable value.
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).
I don't want to freeze the object, I want to have a handle that doesn't allow me to modify the object. (Whether that would be at all possible in JS is another question.)
So
let foo = {field:1};
immutable let bar = foo;
bar.field = 2; // error
foo.field = 3; // ok
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; }`.)
I agree that having a "can't modify this object" via this reference is useful and that JavaScript doesn't have it. TypeScript has it with `ReadOnly<T>`
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.
That sounds like a fundamental mis-understanding. Variables do not hold objects, they hold references to objects.
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.
makes foo const. If you wanted a shortcut for making the object constant (vs Object.freeze) it would be something like 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).