Immutability

One of the cornerstones of functional programming is that so called variables can be assigned only once. This is known as immutability. ECMAScript 2015 supports a new keyword, const. The const keyword can be used in the same way as var except that variables assigned with const will be immutable. For instance, the following code shows a variable and a constant that are both manipulated in the same way:

let numberOfQueens = 1;
const numberOfKings = 1;
numberOfQueens++;
numberOfKings++;
console.log(numberOfQueens);
console.log(numberOfKings);

The output of running this is the following:

2
1

As you can see, the results for the constant and variable are different.

If you're using an older browser without support, then const won't be available to you. A possible workaround is to make use of the Object.freeze functionality which is more widely adopted:

let consts = Object.freeze({ pi : 3.141});
consts.pi = 7;
console.log(consts.pi);//outputs 3.141

As you can see, the syntax here is not very user-friendly. Also an issue is that attempting to assign to an already assigned const simply fails silently instead of throwing an error. Failing silently in this fashion is not at all a desirable behavior; a full exception should be thrown. If you enable strict mode, a more rigorous parsing mode is added in ECMAScript 5, and an exception is actually thrown:

"use strict";
var consts = Object.freeze({ pi : 3.141});
consts.pi = 7;

The preceding code will throw the following error:

consts.pi = 7;
          ^
TypeError: Cannot assign to read only property 'pi' of #<Object>

An alternative is the object.Create syntax we spoke about earlier. When creating properties on the object, one can specify writable: false to make the property immutable:

var t = Object.create(Object.prototype,
{ value: { writable: false,
  value: 10}
});
t.value = 7;
console.log(t.value);//prints 10

However, even in strict mode no exception is thrown when attempting to write to a non-writable property. Thus I would claim that the const keyword is not perfect for implementing immutable objects. You're better off using freeze.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset