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();

 

 

 

 

The output "First Third Second" makes sense when you consider the synchronous and asynchronous nature of JavaScript.

  1. bar() schedules a callback function using setTimeout, which will be executed asynchronously after a certain delay.
  2. foo() is called next, logging 'First' immediately.
  3. baz() is called, logging 'Third' immediately.
  4. After the synchronous execution of foo() and baz(), the event loop moves to check if there are any asynchronous tasks to execute. It finds the callback scheduled by setTimeout in bar().
  5. 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.