JavaScript Interview Question #39: How does setTimeout work inside the loop?
Coderslang: Become a Software Engineer
Posted on May 11, 2021
What will be logged to the console?
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Before we analyze the code snippet, let’s try to simplify it by removing the setTimeout
.
If we just leave the plain console.log
in the loop, then the output is all the values of i
from 0
to 4
printed on each iteration of the loop.
However, when the setTimeout
is added, the console.log
will be executed after the loop has already been processed and the value of i
is 5.
As i
was declared with var
, it has the global scope and the intermediary values aren’t stored in closure around the arrow function () => console.log(i)
.
ANSWER: the value 5
will be printed on the screen 5 times. Each time on the new line.
Posted on May 11, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
April 22, 2021