The snippet runs foo, baz, and a setTimeout in bar. Although bar schedules Second to print, the console shows First and then Third immediately, with Second appearing last as the scheduled callback executes after the synchronous code. This highlights how the event loop handles async callbacks.

Multiple Choice

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

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

The curious dance of JavaScript timing is one of those things you notice only after you stumble into it—like discovering a magic trick you can actually use in real life. If you’ve ever built something in Salesforce using Lightning Web Components or just tinkered with a bit of async JavaScript, you’ve felt that twinge—the sensation that some tasks get done right away while others linger in the wings, waiting for their cue. Let’s unpack that feeling with a simple, relatable example: what really happens when you run code that schedules something for later, while your other lines keep firing now?

A tiny trio that teaches a big lesson

Imagine three tiny functions:

  • foo prints “First.”

  • bar sets a timer to print “Second” later.

  • baz prints “Third.”

If you wire them up so that you call bar(), then foo(), then baz(), the order in which things show up in the console isn’t just “the order you wrote.” There’s a subtle choreography at work—the event loop, the queue of tasks, and how JavaScript handles asynchronous work.

Let me explain the rhythm here, step by step.

Step into the event loop and the queue of tasks

When you call bar(), you’re not immediately printing “Second.” What bar() does is schedule a callback (the one that logs “Second”) to run after the current stack of code completes and the timer, if any, has a chance to pass. In this case, since the timer is set to 0 milliseconds, you might expect “Second” to bounce out right away. But JavaScript isn’t that impatient.

Here’s the truth: setTimeout schedules the callback to run after the current code finishes and after the event loop has a moment to pick up tasks from the macrotask queue (sometimes called the task queue). It’s a queue that collects things like IO events, timers, and other scheduled work. The key is: the current synchronous code wins the race. Once the stack is clear, the event loop looks at the queue and hands control to the oldest item.

So, when bar() runs, it places a “Second” callback into the macrotask queue and returns immediately. The synchronous lines keep marching.

First comes the immediate, then the next

Next up is foo(), which prints “First” without waiting for anything else. It’s the simplest, most reassuring move in the sequence: a direct, immediate log. No phantom delays, no surprises—just a straight line.

Then baz() kicks in, printing “Third.” It’s another synchronous action, finishing its little job before the world has a chance to conjure up the timer callback.

The moment we’ve all been waiting for arrives after the visible work is done

At this point, all the code you wrote synchronously has been executed. The event loop now looks at the macrotask queue and finds the callback that bar() scheduled—the one that logs “Second.” Only then does that piece of code run, printing “Second.” It’s like the curtain falling after the main act has finished: the hidden part completes its moment in the spotlight, but only after the front of the house has finished its business.

So, in practical terms, the visible order is:

  • First (from foo)

  • Third (from baz)

  • Second (from the scheduled setTimeout callback)

That’s why the sequence you’ll observe is First, Third, Second. It’s not just about the code you wrote; it’s about how JavaScript’s single-threaded world hands control to asynchronous tasks and then returns to finish what’s waiting in line.

Why this happens in real-world Salesforce development

You might be thinking, “Okay, great, but where does this matter in Salesforce land?” A lot, actually. Lightning Web Components (LWC) and, to a lesser extent, Aura rely on JavaScript to drive interactive experiences and to coordinate with server calls, user input, and UI updates. Async behavior is not a rare trick; it’s part of the daily routine—fetching data, reacting to events, and ensuring the user interface stays responsive.

Here are a few practical takeaways you can carry into your code:

  • Don’t assume a timer-based log will appear immediately. If you’re scheduling work with setTimeout, plan for it to run after the current stack clears. This helps you avoid “mysterious” ordering bugs where UI updates appear out of sequence.

  • Use the event loop as a mental model. When you see something like setTimeout(() => console.log('X')), think “X will show up after the current execution and other queued tasks.” This mental model is a life-saver when wiring up user actions with server responses.

  • Sequence matters, but not everything needs strict ordering. If you depend on a value produced by an asynchronous operation, you’ll want to chain promises or use async/await instead of assuming a particular log order. In Salesforce code, that often means waiting for a fetch, a wire service update, or a DML operation to complete before acting on the result.

  • Keep the UI snappy. The beauty of asynchronous patterns is they keep the main thread free for user interactions. In LWC, that means your components stay responsive even when there’s a flurry of background work happening under the hood.

A few practical patterns you’ll see in the wild

To make this more concrete, here are some patterns you might use or bump into when building Salesforce apps with modern JavaScript:

  • Chaining async actions with promises. If you have multiple tasks that depend on each other, chaining them with then() or using async/await makes the flow easy to read and reason about. It helps avoid the “callback soup” that can pop up when you nest setTimeout calls.

  • Coordinating UI with data loading. You might trigger a UI update immediately to show a loading indicator, then fetch data, and only after the data arrives update the UI. The timing you see visually should align with the data state, not with the order you started things.

  • Debouncing user input. In an interface with search-as-you-type, you’ll often debounce keystrokes so you don’t fire a server request with every single character. The timing subtlety here mirrors our earlier concept: you’re balancing immediate feedback with delayed, efficient work.

  • Microtasks vs macrotasks—knowing the difference. While your everyday code mostly deals with macrotasks (like setTimeout), there are other tiny, high-priority tasks that get pushed to a microtask queue (think Promise.then callbacks). Microtasks run sooner, often before the next macrotask, which matters when you want to update something immediately after a promise resolves.

A quick detour into the practical why

Okay, you’ve seen the flow. Let’s connect it to a real-world scenario you might recognize in a Salesforce project. Suppose you have a component that, on a user action, needs to show a quick acknowledgement and then fetch more details behind the scenes. You might:

  • Immediately display a “Action received” cue to the user, so they don’t feel stuck.

  • Kick off a server call to retrieve additional data the UI needs.

  • Once the data arrives, update the component’s state and re-render.

If you’re not careful about the timing, you could end up with a moment where the user sees the acknowledgment but the details flicker in later, or you could log something too early and then correct it once the data lands. Understanding the event loop and the queue helps you design interactions that feel natural, not jumbled.

A friendly recap, with a creative twist

Think of JavaScript’s timing as a parade. The main street is your synchronous code—the people who march right away, waving and shouting. The float that promises “Second” is the timer’s callback, waiting behind the scenes in the lineup. When the band finishes its routine (your foo and baz logs), the float finally rolls by. The audience—your users—gets the sense that the show ran smoothly, even though the “Second” moment was technically scheduled a beat later.

If you’re building for Salesforce environments, this mental model isn’t just academic. It’s a practical lens for debugging, architecting clean interactions, and writing code that feels natural to users. You’ll find yourself writing components that respond promptly to user actions while still fetching and integrating data gracefully in the background.

A few tips to keep handy

  • Start simple. If something feels off in order, pause and check whether you’re mixing synchronous and asynchronous work in a way that’s easy to follow.

  • Embrace async/await for readability. When you have chains of asynchronous steps, async/await can make the sequence clearer than a nest of then() calls.

  • Log thoughtfully. Console logs are great for understanding flow during development, but don’t overdo them in production; too many logs can obscure the real timing you care about.

  • Test the timing visually. If you’re working on a UI-heavy piece in LWC, simulate different network speeds or timer delays to see how the component behaves in practice.

A final thought

JavaScript’s timing is one of those things that feels invisible until it’s not. You’ll notice it most when a simple sequence does not print in the exact order you guessed. That moment of realization—“Ah, the event loop did that”—is where your debugging instincts sharpen and your user-facing code becomes smoother. It’s not about beating the clock; it’s about orchestrating the moment so that when the user interacts, the app responds with a calm, confident rhythm.

If you want to explore this a bit more, try playing with small snippets that mix immediate logs with setTimeout calls. Watch how the console fills in. Notice how promises and asynchronous calls behave in relation to timers. It’s a tiny sandbox, but the lessons scale up to real-world Salesforce code—where clean, responsive interfaces aren’t a luxury, but a baseline expectation. And once you’re comfortable with that rhythm, you’ll find yourself building experiences that feel both fast and reliable, every single time.