Over a million developers have joined DZone.

Learning ES6: Using let, const, and Temporal Dead Zone

This post is about the use of let and const keywords to create variables. I'm a big fan of var scope, but I think I'm going to abdicate var scoped variables in favor of let and const. Let me share with you my reasoning...

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

I've finally started to learn EcmaScript 6 (ES2015) and thought it would be good to start writing about it as I learn. There are a bunch of features in ES6 and a good place to start would be to learn the use of let and const. I haven't deeply dived into all the features yet, but I eventually will. This post is about the use of let and const keywords to create variables. I'm a big fan of var scope, but I think I'm going to abdicate var scoped variables in favor of let and const.

The primary difference between var and let scoped variables is their visibility. A var scoped variable is visible throughout the function whereas a let scoped variable is visible only inside the block in which it is declared. Thinking about block scope now, I realize that many times I write if statements and declare variables as required. With var scope, the variable would be visible throughout the function but with let scope, the visibility is limited to the block in which it's declared:

exports.fn1 = function(){
    'use strict';

    console.log('Example 1 - use of let in blocks');

    let a = 10;

    function test() { //new scope, TDZ

        //console.log(a); //throws reference error

        let a = 20;

        console.log(a); // prints 20

            console.log(a); // prints 20

            a = 40; //change in assignment

            console.log(a); // prints 40


        console.log(a); //prints 40, the value of the variable is changed in the block


    console.log(a); //prints 10


let scoped variable is visible in the block in which it's declared and also in child blocks unless the same-named variable is declared in the child block as well. In this example, the variable 'a' (with value 10) is visible throughout the function but not inside function test. Inside function test, a variable with the same name is let scoped, thus overriding the visibility of variable 'a' at the parent function level. Notice that the let scoped variables are visible only in the block in which they are declared. The variables declared in the inner blocks will cease to exist once the execution crosses the block.

On Temporal Dead Zone (TDZ):

Variables declared with var scope are hoisted and return undefined when one tries to access it before it's definition. In the case of let scoped variables, a ReferenceError is thrown. Although, this infers that the let scoped variables are not hoisted, but they are indeed hoisted. See the note here: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-let-and-const-declarations.

It mentions that:

"The variables are created when their containing Lexical Environment is instantiated, but may not be accessed in any way until the variable’s LexicalBinding is evaluated."

From the above statement, a let scoped variable is instantiated, meaning that the variable is hoisted but it's not available until a value is assigned to it. Another example would be:

let a = b, b = 1;

Again a ReferenceError is thrown mentioning that 'b is not defined'. The Temporal Dead Zone starts when the block containing the let scoped variable is encountered and it ends when the definition of the variable is found. In TDZ, the variables would throw a ReferenceError even if the same variable is present in it's enclosing block, i.e. the parent block.

On const:

const scoped variable is similar to a let scoped variable except that it mandates a value to be assigned to it. Any attempt made to change the value of the variable would result in an error. For example, when you use a const variable in a for loop, an error is thrown when you try to increment the value:

for (const i=0; i < 3; i++) {      console.log(i); }

One of the pitfalls I have observed with const scoped variables is that the value that it is bound to is not a constant:

const a = {x: 1}; a.y = 2; //valid const b = [1, 2, 3]; b.push(4); //valid

I'm not sure whether this is the right thing for constants. Although, one can make it non-writeable by using Object.freeze.

Going forward, I would use const for constant variables and for functions which are var scoped by default. Also, let seems to be a good choice over var for scoping variables.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

ecmascript 6 ,javascript ,language constructs

Published at DZone with permission of Sagar Ganatra, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}