I gave a quick talk on JS a while ago on hoisting in JS and while discussing on how hoisting apply to variable declarations, we imminently reached to ES6’s
const. So we began talking about the difference between
const and how
const is not really a constant or immutable.
Constants are block-scoped, much like variables defined using the let statement. The value of a constant cannot change through reassignment, and it can’t be redeclared.
const is not really a constant and it’s not immutable.
The value of a constant cannot change through reassignment, but any object or array stay mutable.
As an object, an array can be frozen; after doing so, its elements cannot be altered and no elements can be added to or removed from the array.
In languages like
C++, for example an object is immutable if it’s declared
const is not about immutability and to make an object’s values immutable you can use Object.freeze().
You might want to read more on this matter:
- MDN docs on const.
- @mathias on why const is not about immutability.
- Last but not least, this Stack Exchange post on the difference between immutable and const is very useful to get the big picture when it comes to other programming languages as C++ and Java.