Sometimes, I want to give a name that never changes meaning, to a value that never changes. No single construct in JavaScript can enforce this.
Someone offline (to DEV, anyway) gave me a really good "But what about this..." example, so I wanted to share it and elaborate a bit on why what my statement still holds.
Basically, they wanted to know why this simple declaration doesn't provide complete immutability:
constx=42;
My answer is that, at least according to my own understanding of JavaScript, it does. However, it is not because of constalone. This declaration creates a box with contents that can be neither replaced nor modified because of two things:
const prevents re-assignments
numbers are immutable value types
If you replaced the initial value 42 with an object (arrays are a kind of JS object), then all of a sudden you've got a mutable value in an immutable variable, and the contents of your const box can be modified because the value itself can be modified:
/* Totally valid but very confusing so I don't like using `const` for this π*/constconfig={some_setting:42};// immutable variableconfig.some_setting="cat";// mutable value
This is what I meant when I said that no single construct in JavaScript can enforce complete immutability. Hope this helps!
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Regarding this statement I made:
Someone offline (to DEV, anyway) gave me a really good "But what about this..." example, so I wanted to share it and elaborate a bit on why what my statement still holds.
Basically, they wanted to know why this simple declaration doesn't provide complete immutability:
My answer is that, at least according to my own understanding of JavaScript, it does. However, it is not because of
const
alone. This declaration creates a box with contents that can be neither replaced nor modified because of two things:const
prevents re-assignmentsIf you replaced the initial value
42
with an object (arrays are a kind of JS object), then all of a sudden you've got a mutable value in an immutable variable, and the contents of yourconst
box can be modified because the value itself can be modified:This is what I meant when I said that no single construct in JavaScript can enforce complete immutability. Hope this helps!