The const keyword of ES6

Hi, in this post I’m going to explain you about the “const” keyword that is part of the Javascript ECMAScript 6 (ES6).

Javascript is constantly updated that’s why we have different version of how write code and “const” is part of this type of updates.

Const is used to declare the read-only variables, that is, the variables whose the value cannot be reassigned.

For example: in Math we have the “pi” that is a value that never change, this means that all the time this value is constant, pi = 3.141

Nice, so in that type of cases we can use “const” in our code to declare values that cannot be reassigned or changed.

Example of pi in code and if we try to change the value of const pi this will cause a exception error:

// declaration of pi as a constant
const pi = 3.141;

// This will cause a exception error because const cannot be reassigned
pi = 3.142;

Which is the scope of the constant?

Constants are block-scoped.

Remember that a block is represented with a pair of curly brackets { } –> block, so the constants values will be accessible through all the block { start – and the end }

Let see this good example with code:

// "a" is a const and the scope is global
const a = 12;

function mySpecialFunction() {
    // I can access to "a" because is in the global scope
    console.log('a --->', a);

    // "b" is just accesible throughout the function because is block-scope of the function --> { }
    const b = 13;
    console.log('b --->', b);

    if (true) {
        // "c" is accesible just inside of this pair of curly brackets because is block-scope of "if" --> { }
        const c = 15; 

        // I can access to "b" because was declared in the block of the function  --> { } and "if" is part of that block too
        console.log('b --inside if-->', b);
    }

    // I can not access to c because is in the block scope of the "if" condition
    console.log('c --->', c); 
} 

mySpecialFunction();

Result:

Objects using “const”

Objects using “const” have special behavior, ok let me explain.

When we assign an object to a variable, the reference of the object is what the variable holds and not the object itself.

So in this case when we assign an object to a constant, the reference to the object become constant to that variable and not to the object itself and that is why the objects are mutables when we use const.

We can modify the object because the reference to the object is constant and not the object itself.

// Object declaration with const
const person = {
    "name": "Cristina"
};

console.log('person --->', person.name); // Cristina

a.name = "Nayeli";

console.log('person --->', person.name); // Nayeli

Result:

And now if we wan to modify the constant we cannot do that because the reference to the object is constant.

// Object declaration with const
const person = {
    "name": "Cristina"
};

// cleaning object
person = {};

Result:

By Cristina Rojas.