# Synchronous vs Asynchronous JavaScript | Execution Context, Call Stack & Single-Threaded | Episode 1

Prefer watching the video first? I recommend watching Episode 1 before reading this article. The video explains the concepts step by step, and this article can be used as a detailed written reference.

<iframe width="560" height="315" src="https://www.youtube.com/embed/Yuh8OCr1-RI" frameborder="0" allowfullscreen>
</iframe>

* * *

## Series Introduction

Welcome to the **Mega Asynchronous JavaScript Series**.

We will build a **complete mental model** of how asynchronous JavaScript works from the ground up.

| Episode | Topic |
| --- | --- |
| 0 | Introduction to the Asynchronous JavaScript Series ✅ |
| 1 | Synchronous vs Asynchronous JavaScript, Single-Threaded, Execution Context and Call Stack |
| 2 | JavaScript Engine and Runtime Environment, V8, Execution and Browser APIs |
| 3 | Asynchronous JavaScript and Event Loop, Timers, Queues, Concurrency and Parallelism |
| 4 | JavaScript Callbacks and Callback Hell |
| 5 | JavaScript Promises, Promise APIs, Polyfill, Project and Interview Questions |
| 6 | JavaScript Async/Await, Promises, Project and Interview Questions |
| 7 | Asynchronous JavaScript, Complete Mental Model, Advanced Questions and Practice |

* * *

## "Why are we starting with synchronous JavaScript?"

You came here to learn **asynchronous** JavaScript. So why synchronous first?

Because **asynchronous JavaScript is built on top of synchronous JavaScript.**

If you do not understand how JS normally executes code (synchronously), you will never truly understand how it handles asynchronous operations.

* * *

## 1\. Synchronous JavaScript

**Synchronous** = one thing at a time, in order.

JS executes code **line by line**, top to bottom. The next line **waits** until the current line finishes.

```js
console.log("First");
console.log("Second");
console.log("Third");
```

Each line runs **only after** the previous one is done. This is synchronous execution.

* * *

## 2\. Asynchronous JavaScript

**Asynchronous** = start something now, do not wait for it to finish, move on.

```js
console.log("First");

setTimeout(function () {
  console.log("Second");
}, 2000);

console.log("Third");
```

`setTimeout` scheduled that function to run after 2 seconds. JS did not wait. It moved to the next line immediately.

> We will explain **how** `setTimeout` works internally (Event Loop, Web APIs, Queues) in later episodes. For now just understand the **behavior**.

* * *

## 3\. Synchronous vs Asynchronous

|  | Synchronous | Asynchronous |
| --- | --- | --- |
| Execution | Line by line, in order | Moves to next line without waiting |
| Blocking | Yes, thread is blocked until the current line finishes | No, thread is not blocked; the callback runs later when ready |
| Example | `console.log()` | `setTimeout()`, `fetch()` |
| Use case | Simple calculations | Network requests, timers, file I/O |

* * *

## 4\. Blocking vs Non-Blocking

**Blocking** = stop everything and wait.

```js
console.log("Start");

// This heavy loop blocks the thread for several seconds
for (let i = 0; i < 3000000000; i++) {
  // doing heavy work...
}

console.log("End");
```

Nothing else can run while that loop is executing. The browser freezes, the UI is unresponsive, everything just waits. This is blocking.

**Non-Blocking** = start it, move on, handle it when ready.

```js
console.log("Start");

setTimeout(function () {
  console.log("Timer done");
}, 2000);

console.log("End");
```

JS did not stop and wait 2 seconds for the timer. It moved on to `console.log("End")` immediately. The timer callback ran later. This is non-blocking.

> **Real-world example:** In Node.js, `readFileSync()` is blocking (the thread waits until the entire file is read) while `readFile()` is non-blocking (it starts reading and moves on, calling your callback when done). Same concept, just with files instead of timers.

* * *

## 5\. When to use which?

| Situation | Use |
| --- | --- |
| Simple math, variable assignments, loops | Synchronous |
| Fetching data from an API | Asynchronous |
| Reading a large file | Asynchronous |
| Adding two numbers | Synchronous |
| Waiting for a user click | Asynchronous |
| Setting a timer | Asynchronous |

**Rule of thumb:**

*   Fast and predictable = synchronous
    
*   Takes time or depends on something external = asynchronous
    

The choice depends on the **use case**.

* * *

## 6\. OS, CPU, Core and Threads

Just the basics we need. Not an OS lecture.

### Operating System (OS)

Specialized system software that manages computer hardware and runs applications.

```plaintext
OS = Kernel + System Utilities + User Interface
```

*   **Kernel**: Core part of the OS that directly manages hardware (CPU, Memory, Disk)
    
*   **System Utilities**: Built-in tools and background services (File Manager, Task Manager etc.)
    
*   **User Interface**: Visual interface (Desktop/GUI) or command line (Terminal/Shell)
    

Examples: Windows, macOS, Linux, Android, iOS

### CPU / Processor

**CPU (Central Processing Unit)**, also called the **processor**. It executes program instructions and runs the operating system.

### CPU Core

A **core** is an individual independent **hardware processing unit** inside the CPU.

*   1 core = can execute 1 thread at a time (at any exact instant)
    
*   4 cores = can execute 4 threads at the same time (truly in parallel)
    

Modern CPUs have multiple cores (2, 4, 8, 16 etc.)

> **Physical Cores**: Actual hardware cores inside the CPU. **Logical Cores**: Virtual cores enabled by Hyper-Threading (Intel) or SMT (AMD). 1 physical core acts like 2 logical cores. Example: 6 physical cores + Hyper-Threading = 12 logical cores.

### Process

A **process** is an active running application or program, a unit of execution. Any program that takes up memory and CPU time so the processor can execute it.

### Thread

A **thread** is a lightweight unit of execution within a process, essentially a **worker** of a process.

*   A process spawns and utilizes threads to perform work
    
*   A thread **shares the memory space** of its parent process (unlike a process which gets its own isolated memory)
    
*   A single thread executes on a **single CPU core** at any given instant
    

### Single-Threaded vs Multi-Threaded

|  | Single-Threaded | Multi-Threaded |
| --- | --- | --- |
| Threads | 1 | Multiple |
| Execution | One task at a time | Multiple tasks at the same time |
| Example | JavaScript | Java, C++, Python (with threading) |

* * *

## 7\. Is JavaScript Single-Threaded?

**Yes.**

JS has one thread, one call stack, one thing at a time.

```plaintext
One Thread → One Call Stack → One Thing at a Time
```

> If JS is single-threaded, how does `setTimeout` work? How do network requests happen without freezing the page? That is what we will answer when we learn about the **Runtime Environment**, **Web APIs** and the **Event Loop**.

* * *

## 8\. Concurrency vs Parallelism (Brief)

> We will explain Concurrency and Parallelism in detail in upcoming **Episode 3**. For now, here are quick definitions:

*   **Concurrency** (*Dealing with multiple things at once*): Managing multiple tasks by switching between them.
    
*   **Parallelism** (*Doing multiple things at once*): Executing multiple tasks simultaneously on multiple CPU cores.
    

* * *

## 9\. Why Understanding JS Execution Matters

To understand async JS you need to know:

1.  How does JS execute your code?
    
2.  Where does it keep track of what is running?
    
3.  How does it manage function calls?
    

The answers: **Execution Context** and the **Call Stack**.

* * *

## 10\. Execution Context

> **"Everything in JavaScript happens inside an Execution Context"**

*   We can assume this **Execution Context** as a big box or a container in which the whole JavaScript code is executed.
    

> 💡 **Shoutout:** When researching how to best explain Execution Context and the Call Stack, Akshay Saini's *Namaste JavaScript* playlist was pure gold. This explanation and code flow is inspired directly by his series. If you haven't watched it, check out the link in the description—the whole series is fantastic!

*   Execution Context has 2 components in it:
    
    1.  **Memory Component** (also known as **Variable Environment**) - It is the place where all variables and functions are stored as key-value pairs.
        
    2.  **Code Component** (also known as **Thread of Execution**) - It is the place where code is executed one line at a time.
        

* * *

### What happens when we run a JS program?

*   **An Execution Context is created!**
    
*   Whenever a JS program is executed, a **Global Execution Context (GEC)** is created, having 2 phases (Memory Creation Phase & Code Execution Phase) that run one after the other to execute the program.
    

```js
var n = 2;

function square(num) {
  var ans = num * num;
  return ans;
}

var square2 = square(n);
var square4 = square(4);
```

*   **In the Memory Creation Phase**, variables and functions are stored as key-value pairs. Variables are assigned (initialized) with a special value (placeholder) called `undefined`. Functions are initialized with their whole function definition (literally the exact code) as it is!
    
*   **In the Code Execution Phase**, the code runs line by line, and actual values are assigned to variables, replacing the `undefined` placeholder.
    
*   **Note:** Whenever a function invocation (fn call) happens, a new Execution Context is created and pushed into the Call Stack.
    
*   When a function (or the program) work is done (code execution phase is completed), it is deleted and popped off from the Call Stack (at last, the GEC is deleted and the program ends).
    

* * *

## 11\. Call Stack

#### **Call Stack** maintains the order of execution of execution contexts.

*   Call Stack is also known as:
    
    1.  Execution Context Stack
        
    2.  Program Stack
        
    3.  Control Stack
        
    4.  Runtime Stack
        
    5.  Machine Stack
        
*   It follows **LIFO** (Last In, First Out):
    
    *   Function **called** → Execution Context created → **pushed** onto the stack
        
    *   Function **finishes** → Execution Context deleted → **popped** off the stack
        

* * *

## 12\. Mental Model Recap

```plaintext
JavaScript is a Synchronous Single-Threaded Language
        ↓
Everything happens inside an Execution Context
        ↓
Execution Context = Memory (Variable Environment) + Code (Thread of Execution)
        ↓
Two Phases: Memory Creation Phase → Code Execution Phase
        ↓
Call Stack maintains the order of execution
        ↓
LIFO: Functions pushed when called, popped when done
```

* * *

## Coming Up in Episode 2

We now know:

*   JS is **single-threaded**
    
*   It has **one Call Stack**
    
*   It executes **one thing at a time**
    

So the question is:

> **If JavaScript can only do one thing at a time, how does asynchronous JavaScript actually work?**

How does `setTimeout` not block the entire program? How do network requests happen without freezing the page?

The answer involves the **JavaScript Engine**, **Runtime Environment**, **Web APIs** and eventually the **Event Loop**.

That is Episode 2. 🚀

* * *
