ES6 Block Scoping

This is the first of a series of blogs on the new features on the upcoming ECMAScript 6 (ES6) specification which JavaScript implements.

In this blog we focus on block level scoping introduced in ES6.

Block scoped variables are done using:

const PI = Math.PI

function foo(a, b) {
    if (a>b) {
        let tmp = b;
        a = PI;
    }
    console.log(tmp===b);    // ReferenceError: tmp is not defined
    return {a, b};
}

The behaviour where tmp throws a ReferenceError in ES6 is tricky because JavaScript previously accepts this flow in ES5. Before ES6, JavaScript only has function level scoping so if we turn let into var then you would still have it declared as undefined and not throw a ReferenceError.

This is because when variables are function level scoped, the compiler moves all variable declarations to the top, this is called hoisting. However in ES6 with block level scoping, we do not initialize an undefined tmp so when we try to get a reference of it in the console.log method it throws a ReferenceError.

P.S. The return value of the function foo() is a sneak peak to the next post on ES6 on object literals.

 
2
Kudos
 
2
Kudos

Now read this

Pricelinelabs: omni-slider

This blog is about my experience building and being the author of the first open source project under Pricelinelabs. The omni-slider is a multi-range vanilla javascript slider widget component released on the open source world in GitHub... Continue →