JavaScript Interview Questions - Asynchronous JavaScript

Last updated on 19 Nov, 2020


What is the output of following code? Also, please provide explanation for your answer.

setTimeout(() => console.log("First"), 0);


In the console, first "Second" will be printed, then "First".


setTimeout works asynchronously. Even though the delay is 0 millisecond, in line 1, only the setTimeout() invocation is happening. That does not execute the callback function passed to setTimeout.

Then in the second line "Second" is printed. After that, the call stack is free to execute the callback function. So it executes and prints "First" in console.