Hacker News new | past | comments | ask | show | jobs | submit login

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.


If you are using TypeCript checkout ReadOnly<T> utility type

https://www.typescriptlang.org/docs/handbook/utility-types.h...




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: