Prepare for the Salesforce JavaScript Developer Exam. Utilize comprehensive quizzes, flashcards, and multiple choice questions with hints and explanations. Boost your exam readiness!

Practice this question and more.


What will be the output when the following code is executed: const foo = () => console.log('First'); const bar = () => setTimeout(() => console.log('Second')); const baz = () => console.log('Third'); bar(); foo(); baz();?

  1. First Second Third

  2. First Third Second

  3. Second First Third

  4. Second Third First

The correct answer is: First Third Second

The code provided defines three functions: `foo`, `bar`, and `baz`. The execution flow of these functions reveals the output order. When `bar()` is called, it invokes a `setTimeout` function that schedules the output of 'Second' to occur after the timer (default is 0 milliseconds) has elapsed. This means that while 'Second' is scheduled, control is immediately returned to the next line of code since it's asynchronous. Next, `foo()` is executed, which immediately outputs 'First' to the console. After that, `baz()` is called, which outputs 'Third' to the console as well. At the end of this sequence, the scheduled function from `bar` will execute and output 'Second' to the console, but only after the synchronous operations (the calls to `foo` and `baz`) have completed. So, in the order of execution: 1. `bar()` schedules 'Second' (but it doesn't log it immediately). 2. `foo()` logs 'First'. 3. `baz()` logs 'Third'. 4. After all synchronous code has executed, 'Second' is logged by the scheduled callback from `bar`. Hence, the final order of outputs is 'First