ES6 part I : Let key word in ES6

Since this is the first post of a series of posts about ECMAScript 6, I'll explain what is ECMAScript is. ECMAScript is the “proper” name for the language commonly referred to as JavaScript. ECMAScript 6 is the latest version of the ECMAScript standard. ES6 is a significant update to the language, and the first update to the language since ES5 was standardized in 2009.

It introduce many new and nice features to make easy programming for programmers.

Let key word

According to description from MDN let keyword allows us to declare variables that are limited in scope to the block, statement, or expression on which it is used.


Lets see what that means.

Example 1

If we declare a variable using var keyword as follows it can be accessed outside of that block (outside if statement)

if(true){
  var greeting ="hello";  
}
console.log(greeting);

But If we use let keyword instead of var, we won't be able to access it outside of the block. console.log(greeting);gives an error

if(true){
  let greeting ="hello";  
}
console.log(greeting);

Example 2

Usually we use var keyword inside a for loop to declare a iterator. But that variable can be accessed outside that for loop as you can see in following example. Because it will print 10 in console.

for(var i=0;i<10;i++){
    
}
console.log(i);
But If we use let keyword to define a iterator it will can be accessed only in the scope of for loop. So following console.log(i); will give an error.

for(let i=0;i<10;i++){
    
}
console.log(i);

some times People use this feature as follows
{
let name="xyz";

...
...

}

So programmer can declare variables as only accessed inside a certain scope and it makes their work easy.

No comments:

Post a Comment