About variable declaration and immutability in Javascript

Variable with scalar values

The let statement defines a simple variable.

let value = 'foo';

That can be re-assigned.

let value = 'foo'; value = 'bar';

Constants

The const statement defines a constant that can't be re-assigned to a different value.

const value = 'foo'; value = 'bar';

If you try it you'll get an error.

Assigning objects to variables

When you instantiate a new object and assign it to a variable: the variable is just a reference to that instance.

So several variables can reference the same instance.

This is true for an Array since it is an object:

let myArray = []; let value = myArray; myArray.push('foo');

In this example there is 2 variables but only 1 array in memory.

So both of the variables can be used to modify the array. And both of the variables will show the array in its new state.

What about constants?

When assigning an object to a constant, the constant will reference the object and won't be able to be re-assigned to anything else.

It will always reference this specific object in memory.

const value = []; value = 'foo';

Why can I modify the object then?

Well... you can have both a variable and a constant referencing the same object!

let anything = []; const value = anything; anything.push('foo'); anything = 41;

What we just did here is:

  1. Create a variable reference to a new object.
  2. Create a constant reference to this object.
  3. Modify the object using the variable.
  4. Change the variable reference to something else.

What's important to understand is that let and const are not defining the behaviour of the object but the type of the reference.

Although a constant is locked on to a specific object, it doesn't make the object immutable.

In fact, there is simply no immutability in Javascript.


Epilogue: Everything is an object

So "why didn't they just" made const declare an immutable object?

Many other languages, like PHP, choose to prevent Objects from being declared as constants and don't offer immutable objects as for now.

Well in Javascript: everything is an object, so nothing is immutable.