8 ms·
Native objects in JavaScript are already immutable as in you can not change them, only create new objects. Const will not make your object immutable! Try this:
by z3t4 10y ago
Native objects in JavaScript are already immutable as in you can not change them, only create new objects. Const will not make your object immutable! Try this:
const foo = {bar: 1}
foo.bar = 2;
It will only avoid having the pointer re-pointed to another object. It's better to just try avoiding global variables, and use a naming convention like uppercase and/or underscore for constants and global variables.
Const is probably only meant for constants like the name suggests.
I think something like this is pretty safe from reassigning:
{
let foo = 1
...
}
...
If you want more control over your properties, you can use the ES5 feature "defineproperty" where you can set writeable: false
- fryan 10y agoconst foo = {bar: 1} The only thing const about it is the reference `foo` cannot be reassigned: foo = something_else; // error Unlike `const` in C++, `const` in javascript in not very useful in my opinion. `let` is shorter and more readable.
- betenoire 10y agoAll true. But what I said was, > it can help you write stateless code if you assume immutability
- gotofritz 10y agoEven that is only true for shallow objects
- hajile 10y agoYou can call `Object.freeze()` if you want immutable properties.