Understanding constants

Constants, or immutable variables, can be defined by using a const keyword. When using the const keyword, the variable content cannot be reassigned:

const PI = 3.14159;

The scope of const is block-scoped, which is the same as let have. It means that the const variable can be used only inside the block where it is defined. In practice, the block is the area between curly brackets { }. The following sample code shows how the scope works. The second console.log statement gives an error because we are trying to use the total variable outside the scope:

var count = 10;
if(count > 5) {
const total = count * 2;
console.log(total); // Prints 20 to console
}
console.log(total); // Error, outside the scope

It is good to know that if the const is an object or array, the content can be changed. The following example demonstrates that:

const myObj = {foo : 3};
myObj.foo = 5; // This is ok
..................Content has been hidden....................

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