This content originally appeared on DEV Community and was authored by Coderslang: Become a Software Engineer
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.
This content originally appeared on DEV Community and was authored by Coderslang: Become a Software Engineer
Coderslang: Become a Software Engineer | Sciencx (2021-05-11T12:27:06+00:00) JavaScript Interview Question #39: How does setTimeout work inside the loop?. Retrieved from https://www.scien.cx/2021/05/11/javascript-interview-question-39-how-does-settimeout-work-inside-the-loop/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.