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.
If we declare a variable using var keyword as follows it can be accessed outside of that block (outside if statement)
Lets see what that means.
Example 1
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