-1

for below code output will print "3" for 3 times, i.e updates same variable for 3 times

for(var k=0;k<3;k++){
 setTimeout(()=>{
      console.log(k)
    },1000) 
}

similarly if i use let instead of var 1,2,3

for(var k=0;k<3;k++){
 setTimeout(()=>{
      console.log(k)
    },1000) 
}

i know why it prints 0,1,2 as i is different every time. i'm just wondering why its printing 3 in case of var as condition is to checking for less then 3?

SameerShaik
  • 488
  • 2
  • 10
  • 22

2 Answers2

0

The above result is because, var defines variable globally, or locally to an entire function regardless of block scope.

let creates a variable declaration for each loop which is block level declaration. So basically it creates a scope within { }.

If you want to print using var keyword use self invoked functions :

for(var k=0;k<3;k++){

(function(k){

 setTimeout(()=>{

      console.log(k)

    },1000) 

})(k);

}

Kasunt
  • 45
  • 1
  • 10
0

the function setTimeout will execute after the delay provided. The code execution doesn't stop since the javascript is based on concurrency model and event loop, so the execution continues till the delay provided. which in case, increment the k. Also, the post-increment operator will use the value before iteration. So, for last iteration the value of k is 3, but since we have given a delay, it would print 3 every time.

toxdes
  • 421
  • 4
  • 8