Wednesday, 16 August 2017

What is the performance difference between 'let' and 'var' in JavaScript?

‘let’ is included in the ECMA script 6th Edition in purpose to define variable for a specific scope of block. ‘var’ is usually used when you have to use it for global scope.
‘var’ variables can be used in the window scope and ‘let’ variables cannot be used in it.
Say, here we have two variables declared. let us see what output it actually gives you.
Thus let variables cannot be accessed in the window object because they cannot be globally accessed.
let variables are usually used when there is a limited use of those variables. Say, in for loops, while loops or inside the scope of if conditions etc. Basically, where ever the scope of the variable has to be limited.
For eg -
The output will be -
Now lets use var keyword instead of let and see what happens -
And the output? What do you think? It should throw an error right. But it does not. Look at this -
And if you do the same thing with the ‘let’ variable, it shows the following error -
This happens there was access of i variable out of the scope.
I hope this helps.

No comments:

Post a Comment