While practicing javascript I came across with one doubt I am printing variable i value using var and using let keyword and both the time getting different result but unable to understand why I need some explanation for this??
with var i
<script>
(function timer(){
for(let i=0;i<=5;i ){
setTimeout(
function clog(){
console.log(i)
},i*1000 );
}
}
)();
</script>
output ::
while using var
<script>
(function timer(){
for(var i=0;i<=5;i ){
setTimeout(
function clog(){
console.log(i)
},i*1000 );
}
}
)();
</script>
output ::
CodePudding user response:
The reason is simple. let
is block scoped. It means that when you get out of the scope of your for loop, it does not exist. var
scope is wider. What happens here is that the for loop increments i
5 times, then gets out of the loop with i = 6
before the first setTimeout triggers (in less than 1 second) with a global scope. The i
declared with let
is from the function scope, while the i
declared with var is from the outer scope
Difference between let and var: What is the difference between "let" and "var"?
CodePudding user response:
It is because of globally (var) or block scoped (let) value processing of javascript.
In var, variable i is globally changing and the loop finishes before settimeout function runs, so the i becomming 6 globally and console log writes yo it as 6.
In let, for every loop iteration there is an i variable belongs only that scope and settimeout function takes it, so the even if the loop finish it's job console log writes local varible i as 0,1,2,3,4,5.
I hope i tell myself correctly.
ref: Javascript MDN
CodePudding user response:
With for
loop, each iteration has its own scope.
In the case of
let
as itsblock scope
each iteration will have its owni
variable and its value will be closure in thesetTimeout
, so eachsetTimeout
will output the correct indexIn the case of
var
as it's afunctional scope
, each iteration will override the previous one, and at the time of execution of thesetTimeout
the value ofi
will be6
at the end of the iteration, will be logged in all setTimeout callbacks.
CodePudding user response:
The scope of i
is different when using let
and when using var
Here:
for(let i=0;i<=5;i ){ // i will not be available outside of the block below
setTimeout(
function clog(){
console.log(i)
},i*1000 );
// mentionning the variable i will cause a Reference error starting from here
Whereas with var
, i
gets hoisted, and defined without a value at the beginning of current the function's block, at the end of the loop i
still exists, and has been mutated, so by the time the setTimeout
callback is triggered, the loop will be already finished and i
will have its final value, which is the first value not matching the looping condition (i.e. 6
).