OdeToCode IC Logo

The Features of ES6 Part 1: Let

Thursday, July 31, 2014

The next version of ECMAScript is on the way, and I’m  genuinely excited about the changes to the JavaScript language. Thus, a series of posts with code and commentary will commence.

let: The Story

Variable scope in JavaScript has been a source of surprises and bugs over the years. The surprise is because JavaScript only offers function scope and global scope to control the lifetime of a variable. There is no block scope.

var doWork = function(flag){
    if(flag){
        var x = 3;
    }
    return x;
};

var result = doWork(true);
expect(result).toBe(3); // PASS!!!!!

The new let keyword of ES6 will replace var for variable declarations and provide true block scoping.  

var doWork = function(flag){
    if(flag){
        let x = 3;
    }
    return x; // ReferenceError: x is not defined
};

// Prepare for runtime error ...
var result = doWork(true);
expect(result).toBe(3);  

 

Iteration statements also benefit from let.

var doWork = function(){
    for(let x = 0; x < 3; x++) {
        // ...
    }
    return x; // ReferenceError: x is not defined
};

let: The Significance

The var keyword is still supported in ES6, but should be thought of as an obsolete keyword when writing ES6 code.

let is the new var!

Will let make JavaScript code better?

I doubt if let will prevent a significant number of bugs, but I do think JavaScript code will improve.

  • We can declare variables close to where they are needed instead of declaring all local variables at the top of a function, which is a defensive practice followed today to avoid var related bugs.
  • We don’t need to introduce a second nested function or IFFE only to control the scope of a variable (another defensive practice you’ll see in JS libraries).

The end result is code using let should be easier to read, and perhaps just a tiny bit safer, too. Next up we’ll look at const, and eventually move on to some of the prime movers for a paradigm shift in JavaScript programming.

Want more? Watch JavaScript Fundamentals for ES6 on Pluralsight!