DEV Community

Discussion on: Once and for all: const in JavaScript is not immutable

Collapse
 
prahladyeri profile image
Prahlad Yeri

That's just because of the nature of JavaScript, that's how it is.

In JavaScript, some built-in types (numbers, strings) are immutable, but custom objects are generally mutable.

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):

Object.defineProperty(person, 'name', { value: 'John', writable: false });

So when you do this, it'll be silently ignored since the person object is now immutable:

person.name = "Valentino";

This is irrespective of whether you defined person as let, const or var!

Collapse
 
valentinogagliardi profile image
Valentino Gagliardi

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

Collapse
 
nicknapoli82 profile image
Nicholas Napoli • Edited

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.