Predict the output of the following javascript code
const foo = () => console.log('First');
const bar = () => setTimeout(() => console.log('Second'));
const baz = () => console.log('Third');
bar();
foo();
baz();
Quiz Explanation
The output "First Third Second" makes sense when you consider the synchronous and asynchronous nature of JavaScript.
bar()
schedules a callback function usingsetTimeout
, which will be executed asynchronously after a certain delay.foo()
is called next, logging 'First' immediately.baz()
is called, logging 'Third' immediately.- After the synchronous execution of
foo()
andbaz()
, the event loop moves to check if there are any asynchronous tasks to execute. It finds the callback scheduled bysetTimeout
inbar()
. - Finally, the callback function from
setTimeout
is executed, logging 'Second'.
This explains why 'First' and 'Third' are logged synchronously, and 'Second' is logged asynchronously, appearing after the other two messages are already logged.