Immutability

Another important principle of FP is immutability. Modifying state and data generates cyclomatic complexity and makes any computer program prone to bugs and to inefficiency in general. Indeed, all variables should, in fact, be immutable. A variable should never change its value, from the moment it is allocated to memory until the moment it is deallocated, in order to avoid changing the state of the application.

Since ES6, it is now possible to use the const keyword to define a constant or immutable variable. Here is an example of its usage:

function myJS()
{
const number = 7;

try {
number = 9;
} catch(err) {
        // TypeError: invalid assignment to const 'number'
console.log(err);
}
}

This added feature now makes it possible to prevent the modifications of variables through assignments. This way, it is possible to protect a JavaScript application's state from mutation during its entire runtime.

Whenever possible, the developer should always prefer using const over let or var. Trying to modify a variable that was declared using the const keyword will cause the following error (chap8_js_const_1.html):

Assigning to a constant variable causes a 'TypeError'
..................Content has been hidden....................

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