Block-Scoped Functions in ECMAScript 6


Image above clearly shows how does scope is nesting in JavaScript.
In JavaScript ECMAScript 5 every scope it is a scope of function. Blocks, like if{}else{}, are not creating their own scope.

If you want to make your function block-scoped in ES5 you’ll have to nest it to another function.
But in ECMAScript 6 you have better solution!

This is the way we’d write in ESCMAScript 5:

    (function(){
        function privateFunc(){
            console.log("You cannot reach me outside this scope");
            (function(){
                console.log("You cannot reach me even from privateFunc");
            })();
        }
        privateFunc();
    })();

And here is ECMAScript 6 block-scoped functions:

    {
        function privateFunc(){
            console.log("You cannot reach me outside this scope")
            {
                console.log("You cannot reach me even from privateFunc")
            }
        }
        privateFunc()
    }

As you see, everything between a curly brackets { & } has own scope in ECMAScript 6!