const

The const keyword is used to define a variable whose value shouldn’t change. If you intend to modify the value in a variable, then define it using let; otherwise, define it using const.

Here’s an example that shows the difference between using let and const:

 //BROKEN CODE
 'use strict'​;
 let​ price = 120.25;
 const​ tax = 0.825;
 
 price = 110.12;
 
 tax = 1.25;

There’s no issue changing the value of the price variable. However, since tax is defined as a constant, we will get a runtime error when we try to modify the value:

 tax = 1.25;
  ^
 
 TypeError: Assignment to constant variable.

Reach of const

Before we declare const as one of the most awesome features in modern JavaScript, let’s understand its limitations. Only primitive values, like number, and references to objects are protected from change. The actual object that the reference refers to does not receive any protection from the use of const.

Let’s take a closer look at the limitations with an example:

 const​ max = 200;
 const​ ok = ​true​;
 const​ nothing = ​undefined​;
 const​ nope = ​null​;
 const​ sam = { first: ​'Sam'​, age: 2 };
 
 //max = 200; //Not allowed
 //ok = true; //Not allowed
 //nothing = undefined; //Not allowed
 //nope = null; //Not allowed
 
 //sam = { first: 'Sam', age: 2 }; //Not allowed
 
 sam.age = 3;

The variable max, of type number, is defined as a constant variable and initialized to a value of 200. The value of max is now set permanently, like my opinions of politicians. We can’t legally place max on the left-hand side of the equals sign, even under the pretense of resetting it to the value it already contains. The same is the case with ok, which is of type boolean, and nothing, which is of type undefined. nope and sam are references and can’t be altered.

JavaScript const is like final in Java and readonly in C#—all of these protect only primitives and references. None of these protect the object being referenced. In the previous example, the reference sam is a handle to an object with two properties: first and age. While the const prevents us from changing the reference sam, it does not care about any change to the internals of the object. Thus, setting the age of sam to a different value had no issues.

To make a reference immutable, use const. However, to make an object itself immutable, we need some additional help from JavaScript.

Making Objects const

It’s great that primitives and references can be made immutable using const. However, any arbitrary function may modify the properties of an object even if the object was intended to be unchanged. There’s thankfully a way to prevent changes to an object. Let’s examine an object that’s already immutable before we see how to bring that feature to our own objects.

 //BROKEN CODE
 const​ greet = ​'dude'​;
 console.log(greet);
 
 greet[0] = ​'r'​;
 console.log(greet);

A constant variable named greet is given a value dude at the start of the function. Then we change the value of the first element in the string instance. Let’s take a look at the output from the code:

 dude
 dude

The value held in the object referenced by the greet variable is the same before and after the change. Strangely, the change had no effect at all. That’s because objects of string are immutable in JavaScript.

JavaScript silently ignored the change to the immutable object instead of yelling out—it treats us like we treat our guests. We can change this behavior by including the ’use strict’; directive, like so:

 //BROKEN CODE
 'use strict'​;
 
 const​ greet = ​'dude'​;
 console.log(greet);
 
 greet[0] = ​'r'​;
 console.log(greet);

Now, when we modify the string instance, we get a stern error:

 greet[0] = 'r';
  ^
 
 TypeError: Cannot assign to read only property '0' of string 'dude'

A code that fails loudly is better than the one that misbehaves quietly—’use strict’; came to our rescue yet again.

The reference greet is immutable since we declared it const, but the actual instance is also immutable. That’s intriguing; if they can do that for string, we should be able to do that for our own instances. The answer is the freeze() method in Object. Let’s use that to make immutable the sam object we saw earlier.

 //BROKEN CODE
 'use strict'​;
 
 const​ sam = Object.freeze({ first: ​'Sam'​, age: 2 });
 
 //sam = {}; //ERROR, the reference sam is immutable
 
 sam.age = 3;
 
 console.log(sam.age);

Right after we created the object, we passed it through the freeze() method of Object. This returns a reference to an object that is immutable. We assign the reference to a constant variable named sam. Now, the reference is immutable thanks to const. Furthermore, the object itself is immutable due to freeze(), as we see from the output:

 sam.age = 3;
  ^
 
 TypeError: Cannot assign to read only property 'age' of object '#<Object>'

There’s a caveat in using the freeze() method, however. It is a shallow freeze, not deep. The freeze() method makes only top-level properties of an object read-only. If a property in turn refers to another object, instead of a primitive type, then that nested object is not made read-only by the call to the freeze() method.

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

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