Last Updated: March 07, 2016
·
563
· satish860

JavaScript V Next - 'let' keyword

In previous versions of JavaScript a variable can be scoped in two level

  1. Global Scope
  2. Function Scope

There is a no blocked scoping available in the language before .So what is mean by blocked scoping

In most language braces({}) creates the scope for the variable. variables live and die inside the scope of the variable. But not in JavaScript,Look at the example below

For Example

var x = 2; //I am global scope
var functionScope = function (flag) {
    if (flag) {
        var scopedVariable = 3;
    }
    return scopedVariable
}
console.log(x); // Prints 2 out
console.log(functionScope(true)); // prints 3 out !! Why 
console.log(functionScope(false)); //Prints undefined !! Why    

Look at the way "scopedVariable" inside the function works even though it is declared inside the braces it can be used outside for returning the result . It is because of the function scoped nature of the language . It is also called variable hoisting(Jargon)

This is being criticized as one of poor feature of the language and good enough to confuse most programmers who are coming from other language.

Solution

"let" keyword comes for the rescue which brings the block scoping to the language and provide a better way to understand the program. Here is retake on the example above

var x = 2; //I am global scope
 var functionScope = function (flag) {
     if (flag) {
         let scopedVariable = 3;
     }
     return scopedVariable
 }
 console.log(x); // Prints 2 out
 console.log(functionScope(true)); //throws error
 console.log(functionScope(false)); //throws error

"let" keyword implementation throws are compile error(in browser) just like the other language instead of providing undefined . This feature will make the programmers from other languages more comfortable and as a language it will bring bit more safety to use.
To play with this feature use the below setting

Traceur setting

As pointed out in my previous blog ES6 is not implemented in all the browser . So to experiment with the features you need use a external library called Treceur . Since "let" is one of experimental feature we need to make it explict. This can be done using

<script>
traceur.options.experimental = true;
</script>

Nothing ends with out the plunker and example for everyone to work with .
http://plnkr.co/edit/nEgd1Uni4vnSXAEqLVpS?p=preview

Best practices for Es6

Always use 'let' for variable declartion to avoid the confusion

1 Response
Add your response

good to know, thanks

over 1 year ago ·