Keyword 'const' does not make the value immutable. What does it mean?

There's the const definition in Exploring ES6 by Dr. Axel Rauschmayer:

const works like let, but the variable you declare must be immediately initialized, with a value that can’t be changed afterwards. […]

const bar = 123;
bar = 456;  // TypeError: `bar` is read-only

and then he writes

Pitfall: const does not make the value immutable

const only means that a variable always has the same value, but it does not mean that the value itself is or becomes immutable.

I am little confused with this pitfall. Can any one clearly define the const with this pitfall?


When you make something const in JavaScript, you can't reassign the variable itself to reference something else. However, the variable can still reference a mutable object.

const x = {a: 123};

// This is not allowed.  This would reassign `x` itself to refer to a
// different object.
x = {b: 456};

// This, however, is allowed.  This would mutate the object `x` refers to,
// but `x` itself hasn't been reassigned to refer to something else.
x.a = 456;

In the case of primitives such as strings and numbers, const is simpler to understand, since you don't mutate the values but instead assign a new value to the variable.


MDN sums it up nicely:

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in case the content is an object, this means the object itself can still be altered.

More succinctly: const creates an immutable binding.

In other words: const, like var, gives you a mutable chunk of memory in which you're storing something. However, const dictates that you must keep referring to that same chunk of memory – you can't reassign the variable to a different chunk of memory, because the variable reference is constant.

To really make something constant and unchanging after you've declared it, you need to use something like Object.freeze(). However, that's shallow and only works on key/value pairs. Freezing an entire object takes a bit more effort. To do so repeatedly in a performant way is yet more challenging. If you really have a need for that, I'd recommend checking out something like Immutable.js