Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 834
Mukund Kumar Avatar asked Mar 16 '17 12:03

Mukund Kumar


People also ask

Is const variable makes the value immutable?

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.

What does the keyword const mean?

The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.

Is immutable same as const?

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.

What does it mean to be immutable in JavaScript?

Immutables are the objects whose state cannot be changed once the object is created. Strings and Numbers are Immutable.


1 Answers

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.

like image 192
Candy Gumdrop Avatar answered Sep 20 '22 07:09

Candy Gumdrop