Question discussion

What is the output of the following JavaScript code?for (var i = 0; i < 3; i++) setTimeout(() => console.log(i), 0); for (let j = 0; j < 3;…

2189Medium DSSSB TGT Computer Science 0 replies 1 views
0

What is the output of the following JavaScript code?

for (var i = 0; i < 3; i++) setTimeout(() => console.log(i), 0);
for (let j = 0; j < 3; j++) setTimeout(() => console.log(j), 0);
  • A0 1 2 0 1 2
  • B3 3 3 0 1 2
  • C3 3 3 3 3 3
  • D0 1 2 3 3 3
Correct answer: B

Explanation

The var loop shares one variable that is 3 when the timers fire, while let creates a new binding for each iteration; the timers run in the order they were set.

Discussion 0

Nobody has replied yet. Start the discussion!