ECMAScript 2015 – var, let, and const

In ECMAScript 2015 there are two new variable types, let and const.

Const is what it sounds like, a constant whose value cannot be changed after it has been defined.

It is a little trickier to understand the difference between let and the old type var.

There is a good explanation for it at Stack Overflow, but for the quick and dirty explanation, examine the following code:

function loopDeLoop(arr) {

    console.log(`first var_Variable: ${var_Variable}`);
    console.log(typeof let_Variable !== 'undefined' ? `first let_Variable: ${let_Variable}` : `first let_Variable is not defined`);

    for (var var_Variable = 0; var_Variable < arr.length; var_Variable++) {
        console.log(`var_Variable inside loop: ${var_Variable}`);
    }

    console.log(`middle var_Variable: ${var_Variable}`);
    console.log(typeof let_Variable !== 'undefined' ? `middle let_Variable: ${let_Variable}` : `middle let_Variable is not defined`);

    for (let let_Variable = 0; let_Variable < arr.length; let_Variable++) {
        console.log(`let_Variable inside loop: ${let_Variable}`);
    }

    console.log(`last var_Variable: ${var_Variable}`);
    console.log(typeof let_Variable !== 'undefined' ? `last let_Variable: ${let_Variable}` : `last let_Variable is not defined`);

}

loopDeLoop([1, 2, 3]);
In this function we only define the two variables var_Variable and let_Variable when we execute the loops. However, look at what it outputs:
// first var_Variable: undefined
// first let_Variable is not defined

// var_Variable inside loop: 0
// var_Variable inside loop: 1
// var_Variable inside loop: 2

// middle var_Variable: 3
// middle let_Variable is not defined

// let_Variable inside loop: 0
// let_Variable inside loop: 1
// let_Variable inside loop: 2

// last var_Variable: 3
// last let_Variable is not defined

As we can see, the first instance of var_Variable returns ‘undefined’. This means that there is a variable called var_Variable, but it does not have a value as of yet.

When we give it a value in the loop, and then change the value inside the loop, we see that its value changes, and then remains the same throughout the rest of the function.

However, if we try the same thing with the let_Variable, it throws an error. There simply is no variable called let_Variable, and if we did not check its typeof, then we would get the error “Uncaught ReferenceError: let_Variable is not defined”.

Also, we have to do this every time we try to reference it except inside the loop where we have defined it which is the only place where it can actually be said to exist.

Leave a Reply

Your email address will not be published. Required fields are marked *