-3

What should be the output of the following program and kindly explain the code as well.

console.log("first");
setTimeout(() => {
  console.log("second");
}, 0);
console.log("third");
Satpal
  • 132,252
  • 13
  • 159
  • 168
  • Maybe this answer your question https://stackoverflow.com/questions/779379/why-is-settimeoutfn-0-sometimes-useful – Aalexander Jan 28 '21 at 06:57
  • 3
    @Satpal and others. It seems he is not interested in the answer but boosting each other points with muhammad. you can see other questions with the same pattern: OP, and Muhammad Arqam answering with huge upvote in really basic questions: https://stackoverflow.com/questions/65908110/javascript-provide-many-types-of-the-loops-like-for-forreverse-for-of-for/65908526#65908526 | https://stackoverflow.com/questions/65655010/dynamic-editable-input-fields-in-react-js/65655047#65655047 – buzatto Jan 28 '21 at 07:07
  • 2
    @buzatto it's a voting ring. Other possible sockpuppets: https://stackoverflow.com/users/15028069/virtual-dev and https://stackoverflow.com/users/14978010/sunnatwelfare – adiga Jan 28 '21 at 07:40

2 Answers2

0

In this scenario, it should have the below output:

"first";
"third";
"second";

Detailed explanation is in the link: https://www.geekabyte.io/2014/01/javascript-effect-of-setting-settimeout.html

Sarvesh Mahajan
  • 914
  • 7
  • 16
0

The output will be like this:

first third second

Reason: Actually this is the combination of both stack and the queue. Each statement will run in sequence but "SetTimeOut" will push the specific line in the stack within the queue that will be executed after the time. Although it has zero second, still due to stack, it will run after the next instruction.

Muhammad Arqam
  • 119
  • 1
  • 5
  • 13