How JavaScript Works - Behind the Scenes

Take a deep dive into how JavaScript executes, including the event loop, call stack, and memory management!

Introduction

Ever wondered how JavaScript actually executes code? How does it handle asynchronous operations? Let's learn about the call stack, event loop, memory heap, and more!

What You Will Learn

  • JS runtime components (engine, memory, event loop)
  • The call stack and execution context
  • The event loop and how async works
  • Memory management and garbage collection
  • Visual explanations of how everything fits together

Prerequisites

JavaScript Runtime Components

A JavaScript runtime has:

  1. JS Engine: Compiles/executes code
  2. Memory Heap: Stores objects, variables, etc.
  3. Call Stack: Tracks function calls
  4. Web APIs: Provided by browser/Node (DOM, fetch, etc.)
  5. Task Queue: Holds callbacks
  6. Event Loop: Coordinates everything

Call Stack & Execution

JavaScript is single-threaded, with one call stack!

Call Stack Example

function third() {
  console.log('Third!');
}
function second() {
  third();
}
function first() {
  second();
}
first();

Call stack steps:

1. first() is pushed → Stack: [first]
2. first() calls second() → Stack: [first, second]
3. second() calls third() → Stack: [first, second, third]
4. third() executes and logs, then pops → Stack: [first, second]
5. second() pops → Stack: [first]
6. first() pops → Stack: []

Visualizing the Call Stack

graph TD
    subgraph Call Stack
    T1[third]
    T2[second]
    T3[first]
    end
    T1 -->|"pops after return"| T2
    T2 -->|"pops after return"| T3

The Event Loop

This is how JavaScript handles asynchronous code!

  1. Call stack executes code
  2. When an async function runs, it goes to Web API
  3. When Web API finishes, callback goes to Task Queue
  4. When call stack is EMPTY, event loop pushes callbacks to stack!

Event Loop Visualization

graph LR
    A[Call Stack] -->|Empty?| B{Event Loop}
    C[Web APIs] -->|Callback| D[Task Queue]
    B -->|Take from queue| A
    D --> B

Example: Asynchronous Code

console.log('1');

setTimeout(() => console.log('2'), 0);

console.log('3');

Output will be: 1, 3, 2! Because setTimeout goes to Web API, callback to queue, and event loop waits for call stack to empty!

Memory Management

JavaScript automatically manages memory with a garbage collector!

Memory Life Cycle

  1. Allocate: Memory is allocated when you create variables, objects, functions
  2. Use: Use the memory
  3. Release: Garbage collector frees memory when no longer needed

Garbage Collection: Mark & Sweep

The engine marks objects that are still reachable, then sweeps (frees) unmarked ones!

graph TD
    A[Roots Global Variables] -->|References| B[Object 1]
    A -->|References| C[Object 2]
    B -->|References| D[Object 3]
    E[Unused Object] -->|No References!| F[Garbage Collected]

Visual Diagram: Full JS Runtime

graph TB
    subgraph "JavaScript Runtime"
    direction TB
    A[JS Engine] --> B[Call Stack]
    A --> C[Memory Heap]
    end
    
    subgraph "Browser/Node APIs"
    D[DOM]
    E[fetch]
    F[setTimeout]
    end
    
    G[Task Queue]
    H[Event Loop]
    
    B -->|Empty?| H
    D --> G
    E --> G
    F --> G
    G --> H
    H -->|Push to stack| B

Best Practices

  1. Avoid blocking the event loop: Don't run heavy sync code
  2. Prevent memory leaks: Remove event listeners, clean up references
  3. Use async/await for cleaner async code: Easier to read
  4. Use DevTools: Debug call stack and memory issues

Common Mistakes

  1. Blocking the main thread: Long sync functions freeze the UI!
  2. Memory leaks: Forgotten event listeners, global variables
  3. Callback hell: Nested callbacks, fixed by promises/async-await

Performance Notes

  • Keep functions small and fast
  • Avoid unnecessary reflows
  • Use Web Workers for heavy tasks in browsers!

Security Notes

  • Don't leak sensitive data in closures
  • Be careful with eval and user input
  • Sanitize everything!

SEO Notes

"How JavaScript works" is a super common search query!

FAQs

Q: Is JavaScript single-threaded? A: Yes! The main JS thread is single-threaded, but APIs and workers can run in parallel!

Q: What is the event loop? A: The mechanism that handles async code!

Q: What is a memory leak in JS? A: When memory isn't freed even though it's no longer needed!

Q: How does garbage collection work? A: Mark and sweep! Finds unreachable objects and deletes them!

Summary

JavaScript uses a call stack, memory heap, event loop, and Web APIs to execute your code! Understanding this helps you write better, faster, bug-free JS!

Related Articles

Previous Tutorial

JavaScript Engines

Next Tutorial

Let's learn client vs server-side JS! → Client Side vs Server Side JavaScript