I know that's been said hundred of times, but I still see people proclaiming (even in some JavaScript books) that const is immutable. It is not.
...
For further actions, you may consider blocking this person and/or reporting abuse
The thing is const never let you to change the memory address it refers to.
you but can mutate the value itself.
Const makes the reference immutable, and for primitives that means the value is immutable too.
But for Objects, the difference matters.
yes!
That's just because of the nature of JavaScript, that's how it is.
So, it matters not whether you've declared them as const or not, what matters is whether they are custom objects (like in your example) or simple numbers/strings. The latter are obviously immutable whether you use const or not.
And even with your custom object, you can make individual attributes immutable like this (again, const doesn't matter here):
So when you do this, it'll be silently ignored since the person object is now immutable:
This is irrespective of whether you defined
person
aslet
,const
orvar
!My point is that there are people out there still saying "const is intrinsically immutable". While it's not. As for objects >> Protecting objects from manipulation
I would argue that const is intrinsically immutable. Posing the argument that making a reference immutable, but the data inside is not, is not relevant. Granted. It would be nice if this were default behavior, but knowing why the data inside is not const is important.
This flows down to the engine that js is running on in lower level language land, and that land explains this concept of why well. It should not be a debate.
If you want immutability then you need to start using Object.freeze() and Object.seal()
Object.freeze
is shallow though :-)So that's why there libraries like Immutable.js, but it would be great if JS has something for making values immutable.
It's all a war of semantics. Technically, the variable itself is immutable for its lifetime; it just so happens to act as a gateway to data that is quite mutable. This is why I hate the way Java tries to teach students: "Everything is pass by value." Yeah, everything is pass by value... but the value happens to be a reference to something else. Strange that something passed by "value" lets me trigger side effects for observers of that data.
Good post.
I think
const
as an immutable pointer. You can change the value of what it points to but not the place it points to.Disclaimer, that is just how I think about it, I don't know if it works like that internally.
We have to be sure what exactly const are pointing to, the memory address remains the same.
I just learned so much