var and let

//why the outputs looks deffrent?

for (let index = 0; index <5; index++) {
  setTimeout(() => {
    console.log(index)
  }, 1000);
}

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

This is the difference between function scoping (var) and block scoping (let).

1 Like

You should show, or at least explain, what the difference is. Maybe even provide a fiddle to show what the code does.

When I try the code, for the version using var, the value of index is 5 for every iteration. That is strange. I get the expected output if I do not use the setTimeout. Scope is a partial explanation but we need to know why setTimeout makes a difference. I do not know.

The value of the index changes for each iteration from 0 → 4.

for (var index = 0; index < 5; index++) {
  console.log(index) // 0 1 2 3 4
}

console.dir(window.index) // 5
console.log(index) // 5

By the time the setTimeouts execute the callbacks e.g.

() => console.log(index)

The value for index is 5

The callbacks holds a reference of index, not a value.

The old workaround pre let and const was to use an IIFE

for (var index = 0; index <5; index++) {
  ((indexValue) => {
    setTimeout(() => {
      console.log(indexValue)
    }, 1000 * (indexValue + 1))
  })(index) // <- index value passed in
}
3 Likes