JavaScript interview question: setTimeout output

Ever get an interview question that seems simple but hides a tricky JavaScript concept? "What's the output of `setTimeout(() => console.log(1), 0); console.log(2);`?" is a classic. The answer isn't "1, then 2." It’s a great test of your understanding of the event loop. 🧠 The `setTimeout` callback, even with a zero-millisecond delay, gets pushed to the Web API and then the callback queue. The JavaScript engine runs all synchronous code on the call stack 𝐟𝐢𝐫𝐬𝐭. So, `console.log(2)` executes immediately. Only after the stack is clear does the event loop pick up the `console.log(1)` from the queue. ⚡ It's a small detail that reveals a huge amount about how asynchronous JS actually works. Have you struggled with this before? #WebDevelopment #DeveloperTips #CodingLife

To view or add a comment, sign in

Explore content categories