📜 ⬆️ ⬇️

ES6 const is not about immunity

The definition of const is misleading, which must be dispelled:

const creates an immutable link to the object , but this does not mean that the value cannot be changed - no, this value can be changed. The following code will not be an error:

const foo = {}; foo.bar = 42; console.log(foo.bar); // → 42 const arr = [0, 20, 30]; arr[0] = 10; console.log(arr); // → [10, 20, 30] 

The only thing that is immutable here is the object reference. const assigns the value ({}) to the variable foo, and guarantees that there will be no new assignment. Using an assignment operator, as well as unary or postfix operators - and ++ will cause a TypeError error.
')
 const foo = 27; //      //  : foo = 42; foo *= 42; foo /= 42; foo %= 42; foo += 42; foo -= 42; foo <<= 0b101010; foo >>= 0b101010; foo >>>= 0b101010; foo &= 0b101010; foo ^= 0b101010; foo |= 0b101010; //  `--`  `++`: --foo; ++foo; //  `--`  `++`: foo--; foo++; 

ES6 const does nothing with data immutability.

So how do you get an immutable value?


Primitive data types such as numbers, strings, booleans, symbols, null, or undefined are always immutable.

 var foo = 27; foo.bar = 42; console.log(foo.bar); // → `undefined` 

To make the data immutable, use Object.freeze () . This method is available to us since the days of ES5.

 const foo = Object.freeze({ 'bar': 27 }); foo.bar = 42; // TypeError exception    strict mode; console.log(foo.bar); // → 27 

But remember that Object.freeze () is superficial, i.e. the frozen object will still have the ability to change the nested objects. On MDN there is an example of a deep freeze, the deepFreeze method, which allows you to make a fully immutable object.

Object.freeze () only works with key-value objects, and there is currently no way to make objects such as Date, Map, or Set immutable.

There is a proposal for immutable data for the future ECMAScript standard.

const vs. let


The only difference between const and let is that const promises - no reassignment will occur.

Given the above, const makes the code more readable. Within scope, const always refers to the same object. Using let no such guarantee. Therefore, the following practice should be followed:

Source: https://habr.com/ru/post/312088/


All Articles