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.
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 };
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.
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!