Single Choice Not Set

QWhat does the following code produce?
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 1);
}

ID: #4848 Basic JavaScript MCQ 189 views
Question Info
#4848Q ID
Not SetDifficulty
Basic JavaScript MCQTopic

Choose the Best Option

Click any option to instantly check if you're correct.

  • A 1 1 1
  • B 3 2 1
  • C 3 3 3
  • D 1 2 3
Correct Answer

Explanation

In this code, we are using a for loop to iterate over a range of values, and we are using the setTimeout() function to log the value of i to the console after a delay of 1 millisecond.
However, the setTimeout() function runs asynchronously, which means that it does not block the rest of the code from executing.
This means that the for loop will complete immediately, and the value of i will be incremented to 3.
Since the setTimeout() function has a delay of 1 millisecond, it will not run until after the for loop has completed.
By the time the setTimeout() function runs, the value of i will already be 3, so it will log 3 to the console three times.

Share This Question

Challenge a friend or share with your study group.