The reason why is because in C, const defines a read-only variable that is not modifiable, whereas in JavaScript, it is not about value immutability. It doesn’t indicate that a variable’s value is constant or read-only. Instead, it creates an immutable binding (a read-only reference to the value) and guarantees that no reassignment will happen. With this being said, the following code will throw an error at run-time.

To understand the concept of variable better, let’s examine the following image where the generic relationship between a variable identifier (or variable name), its value, and the physical memory is being explained.

Variables and memory allocation.

As you can see from the schema, a variable identifier refers to a physical memory cell through an address (reference) in which the assigned value to the variable is stored. A read-only variable doesn’t allow its value to be changed. A read-only reference to the value simply doesn’t allow the variable identifier to be reassigned, but the value held by the identifier itself can still be changed. For instance, in JavaScript, when the value is an object, the object itself can be altered.

How to make a value immutable

Primitive datatypes are always immutable because of their nature. The following code snippet intuitively explains why.

As you can see in the last example, nested objects within a frozen object can still be mutated. To make object values fully immutable, you may want to use a custom deepFreeze() method. Another option is to use Immutable.js, a library which simply doesn’t turn objects into immutables, but rather provides many Persistent Immutable data structures including List, Stack, Map, OrderedMap, Set, OrderedSet and Record.

var, let or const?

In ES6, developers should never use var to define a variable or a constant. In fact, it is now the weakest signal availablewhen you define a variable in JavaScript.

A well-defined variable should not be used to represent multiple concepts. This ensures that the code is cleaner and more understandable. Since JavaScript constmeans that the identifier can’t be reassigned, it is preferable to use const for all the identifiers in the program that are not supposed to be reassigned. However, when the identifiers need to be reassigned, programmers should use let instead. This is generally the case for counters in a loop construct or values swap in algorithm subroutines.

Take home lesson

Recapping the insights: if you code with ES6, use const by default, don’t use var, and use let where rebinding is needed✌️️. If you have any questions on this or updates, please reach out to me on social at Jacopo Daeli.