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?
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 the case where the content is an object, this means the object's contents (e.g., its properties) can be altered.
The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.
Using const only means that the variable will always have a reference to the same object or primitive value, because that reference can't change. The reference itself is immutable, but the value held by the variable does not become immutable.
Immutables are the objects whose state cannot be changed once the object is created. Strings and Numbers are Immutable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With