Search code examples
javascriptarraysvarlet

Javascript Var and Let Usage


 const array = [1, 2, 3, 4];
 for (var index = 0; index < array.length; index++) {
  setTimeout(() => {
    console.log("I am at index " + index);
  });
}

When I use the "var" keyword in the for loop I get the output

I am at index 4
I am at index 4
I am at index 4
I am at index 4

But When I use the "let" keyword in the for loop,

 const array = [1, 2, 3, 4];
 for (let index = 0; index < array.length; index++) {
  setTimeout(() => {
    console.log("I am at index " + index);
  });
}

I am at index 0
I am at index 1 
I am at index 2
I am at index 3

Can anyone tell me what's happening here?


Solution

  • The answer to your question requires you to understand

    var type variable has a function/script scope and due to hoisting its declaration will move up out of the for loop, so it will come into the global scope and on every iteration, it is getting changed and all three closure will share the single variable i from the global lexical scope, whereas if we replace var with let then it will not move outside the for loop being a block-scoped, every iteration is a new block and there will be three different lexical scope for three timeout callback and a shared global scope(which has nothing from our code).