0

for (var i = 0; i < 3; i++) {
  const log = () => {
    console.log(i)
  }
  setTimeout(log, 100)
}

The output it gives is 3 3 3 which I have no idea why. It was asked in an interview and I want to understand the output

j08691
  • 204,283
  • 31
  • 260
  • 272
Pulkit
  • 13
  • 5
  • 1
    What *do* you understand about it? – Scott Hunter Aug 18 '23 at 15:57
  • 1
    It actually gives an error, because `int` is not a keyword. And the actual result depends on whether you used `var` or `let` instead of it. What you describe happens with `var`. [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/q/750486) – VLAZ Aug 18 '23 at 15:57
  • Sorry, in the code it is var and I want to understand why does it give 3 as an output thrice which I get that it runs 3 times since its inside the for loop but why is it 3 always – Pulkit Aug 18 '23 at 16:05
  • Basic answer to why is .... you have a reference to a variable. The function you create is just looking up `i` when it is triggered. It is NOT storing the value of `i` when the function is created. Since the loop finished looping it is now `3` and since the timeouts fire after the loop is done, they all say 3. – epascarello Aug 18 '23 at 16:18
  • So what I understand by this is that in the `function log` the value of i is not stored so the 3rd line `console.log(i)` prints nothing, right? And if this is the case then okay I get this but why does it prints `3` when in the loop value of `i` should be less than 3 so shouldn't it be `2` – Pulkit Aug 19 '23 at 04:51

0 Answers0