ES6 const is not about immunity

Original author: Mathias Bynens
The definition of const is misleading, which should be dispelled:

const creates an immutable reference 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 = {}; = 42;
// → 42
const arr = [0, 20, 30];
arr[0] = 10;
// → [10, 20, 30]

The only thing that is immutable here is the reference to the object. const assigns the value ({}) to the variable foo, and ensures that there will be no new assignment. Using the assignment operator, as well as unary or postfix operators - and ++ will throw 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;
// Унарные `--` и `++`:
// Постфиксные `--` и `++`:

ES6 const does nothing with data immutability.

So how then to get immutable value?

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

var foo = 27; = 42;
// → `undefined`

To make data immutable, use Object.freeze () . This method has been available to us since ES5.

const foo = Object.freeze({
	'bar': 27
}); = 42; // TypeError exception при условии использования strict mode;
// → 27

But remember that Object.freeze () is superficial, i.e. the frozen object will still have the ability to modify nested objects. On MDN is an example of deep-frozen, deepfreeze method that will make fully immutabelny object.

Object.freeze () only works with key-value objects, and currently there is 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 that reassignment will not happen.

Based on the foregoing, const makes the code more readable. Within scope, const always refers to the same object. Using let there is no such guarantee. Therefore, the following practice should be followed:

  • If possible, always use const by default.
  • let use when reassignment is needed
  • var should not be used at all

Also popular now: