Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 62

Sync vs. Async JavaScript

This lesson is built with resources from youtube.com, freecodecamp.org and 1 more site.

Hello! In our last lesson, we explored ES Modules, which allow us to organize our code into separate files. We ended with a look at dynamic import(), a function that loads a module on-demand. This was your first real glimpse into the world of asynchronous programming, a topic we will officially dive into today.

This lesson addresses a fundamental concept in JavaScript: the difference between synchronous and asynchronous code. Understanding this is not just theoretical; it's the key to building fast, responsive applications and is absolutely essential for fetching data in a Next.js app. Our goal is to explain the difference between synchronous and asynchronous code execution in JavaScript.

The Core Idea: One at a Time vs. Do It Later

At its heart, the difference between synchronous and asynchronous is about how tasks are handled.

  • Synchronous (Sync): Tasks are completed one after another. You must wait for the current task to finish before the next one can start. Think of it as a single-file line where you can't move forward until the person in front of you is done.
  • Asynchronous (Async): You can start a task, and while it's running in the background, you can immediately move on to other tasks. When the background task is finished, you get notified and can handle the result.

This diagram gives a simple visual summary of the concept.

Synchronous vs. Asynchronous Execution Flow
In the synchronous model on the left, a process makes a request and is blocked, waiting for the response. In the asynchronous model on the right, the process makes a request but continues its own work, handling the response whenever it arrives.

To understand why this distinction is so critical in JavaScript, we first need to understand a core characteristic of the language.


Part 1: The "Problem" — JavaScript is Single-Threaded

JavaScript is a single-threaded language. This means it has only one call stack and can do only one thing at a time. The call stack is a data structure that keeps track of which function is currently running. When a script calls a function, it's added (or pushed) to the top of the stack. When the function finishes, it's removed (or popped) from the stack.

JavaScript Event Loop -- Visualized!

To make this idea tangible, let's start with a simple, real-world analogy. The video "JavaScript Event Loop -- Visualized!" by ColorCode provides a fantastic, non-technical introduction to this concept.

Watch the first 1 minute and 39 seconds (00:00 - 01:39). Notice the difference between asking a question that can be answered immediately (synchronous) and asking for something that takes time, like getting coffee (asynchronous).

This single-threaded nature is usually fine, but what happens when a task takes a long time? For example, what if we need to perform a heavy calculation or, more commonly, fetch data from a slow network?

If the code is synchronous, the entire program—including the user interface—freezes until that long task is complete. The browser becomes completely unresponsive. This is called blocking.

JavaScript Event Loop -- Visualized!

Let's see this blocking behavior in action. The same video now demonstrates what happens when you run a long synchronous task in the browser.

Watch from 02:10 to 04:34 and then from 05:35 to 10:28. First, you'll see a code example of a blocking, synchronous function that freezes the app (02:10 - 04:34). Next, the video explains the Call Stack in detail, showing how functions are added and removed one by one (05:35 - 08:36). Finally, it visualizes the synchronous code from before on the call stack, clearly showing why it blocks everything else (08:36 - 10:28). Focus on how each function must finish completely before the next one can even begin.

This blocking behavior is unacceptable in modern web applications. Users expect a smooth, interactive experience. This is precisely why we need an asynchronous way to handle things.


Part 2: The Solution — Asynchronous, Non-Blocking Operations

Asynchronous operations allow us to initiate a long-running task without blocking the main thread. We tell the JavaScript environment, "Hey, start this task, and let me know when it's done. In the meantime, I'm going to continue with other work."

How is this possible if JavaScript is single-threaded? The secret is that the JavaScript engine works within a larger runtime environment (like a web browser or Node.js). This environment provides extra features that JavaScript can use, including Web APIs, a Task Queue, and an Event Loop.

Here's the simplified process:

  1. When you call an asynchronous function (like setTimeout), the JavaScript engine doesn't handle it directly. It hands it off to a Web API provided by the browser.
  2. The JavaScript engine immediately pops the setTimeout call off the stack and continues running your synchronous code. Your program is not blocked.
  3. The Web API handles the task (e.g., it waits for the timer to finish). Once complete, it places the callback function (the function you told setTimeout to run later) into the Task Queue.
  4. The Event Loop has one simple job: it constantly checks if the Call Stack is empty. If it is, it takes the first item from the Task Queue and pushes it onto the Call Stack to be executed.

JavaScript Event Loop -- Visualized!

This process is much easier to understand with visuals. Let's return to the ColorCode video to see how our asynchronous coffee example works under the hood.

Watch from 04:34 to 05:07, and then from 10:28 to 15:08. First, see the non-blocking asynchronous version of the code in action (04:34 - 05:07). Notice the app remains interactive. Then, follow the detailed visual walkthrough (10:28 - 15:08). This part is crucial. It introduces the Web API, the Task Queue, and the Event Loop, showing exactly how they work together to prevent blocking.

This model is the foundation of asynchronous JavaScript. Your synchronous code runs to completion first, and only then does the Event Loop start processing the results of any background tasks.

Test your understanding!

You run the following code snippet:

console.log('A');

setTimeout(() => {
  console.log('B');
}, 1000);

console.log('C');

In what order will the letters A, B, and C be logged to the console? Why?

Show answer

The output will be:

A
C
B

Explanation:

  1. console.log('A') is a synchronous operation. It's pushed to the call stack, executed, and 'A' is logged.
  2. setTimeout is an asynchronous operation. It's pushed to the call stack, and its execution hands the timer and the callback () => { console.log('B'); } over to the Web API. The setTimeout call then pops off the stack immediately. The program does not wait 1 second here.
  3. console.log('C') is synchronous. It's pushed to the call stack, executed, and 'C' is logged.
  4. The main script is now finished, so the call stack is empty.
  5. After about 1 second, the Web API's timer finishes, and it moves the callback function into the Task Queue.
  6. The Event Loop sees that the Call Stack is empty and there's a task in the queue. It moves the callback from the queue to the stack.
  7. The callback executes, console.log('B') runs, and 'B' is logged.

Part 3: The Golden Rule — Synchronous Code Always Runs First

A common point of confusion is what happens with setTimeout(..., 0). You might think setting a delay of zero milliseconds would make the code run immediately, but it doesn't. It's still an asynchronous operation.

This example perfectly illustrates the golden rule: The Event Loop will only move a callback from the Task Queue to the Call Stack when the Call Stack is completely empty. This means all the synchronous code in your script must finish running first, no matter what.

Synchronous vs Asynchronous JavaScript

Let's reinforce this with an excellent article from freeCodeCamp that uses animated GIFs to visualize the process. Pay close attention to the setTimeout(..., 0) example.

Read the sections titled 'How the JavaScript Callback Queue Works (aka Task Queue)' and 'The Event Loop'. The animated GIF under the example code main(); is a perfect step-by-step visualization of why f2 logs before f1, even though f1 had a zero-millisecond delay.

Understanding this rule is key to debugging asynchronous code and predicting its behavior correctly. Even with a zero delay, setTimeout places its callback in the queue to be processed after the current block of synchronous code has finished executing.


Conclusion

You've just learned one of the most fundamental concepts in the JavaScript language. Mastering this difference is the first major step toward writing powerful, non-blocking applications.

Key Takeaways:

  • Synchronous (Sync): One task at a time, in order. Long tasks will block the entire program. Execution is managed entirely on the Call Stack.
  • Asynchronous (Async): Start a task, move on to other things, and handle the result later. This is non-blocking.
  • The Async Team: This is made possible by a team of players: the JavaScript Engine (with its Call Stack), Web APIs (which handle tasks in the background), the Task Queue (which holds completed callbacks), and the Event Loop (which moves tasks from the queue to the stack).
  • The Golden Rule: The Event Loop only moves a task from the queue to the stack when the Call Stack is empty. This means all synchronous code in a script runs to completion before any asynchronous callbacks are executed.

Next Up

In our next lesson, we will formalize our understanding of this entire system. We'll create a detailed map of the JavaScript runtime environment, clarifying the distinct roles of the call stack, web APIs, callback queue, and event loop. We'll also discover that there's another, higher-priority queue for handling modern asynchronous operations like Promises, which is the primary tool you will use for data fetching in Next.js.