Lesson 4: How JavaScript Works

What You’ll Learn

In this lesson, learners will understand:

  • What happens when the browser runs JavaScript
  • The basic JavaScript execution model
  • The role of the JavaScript engine, runtime environment, and event loop
  • Why JavaScript is considered single-threaded but asynchronous

Big Idea: JavaScript is Executed Line by Line

When you write JavaScript and open your page in the browser, the browser reads and runs your code from top to bottom, one line at a time. This process is called interpreting, and it’s different from compiled languages like C++.


Step-by-Step: What Happens When You Run JavaScript?

  1. Browser Loads HTML First
    • The browser reads your HTML file and builds the Document Object Model (DOM) — a tree-like structure of the page.
  2. JavaScript Is Loaded
    • When the browser finds a <script> tag, it loads and starts running the JavaScript line by line.
  3. JavaScript Engine Takes Over
    • Each browser uses a JavaScript engine (like Chrome’s V8) to execute the code.
  4. JavaScript Executes Synchronously
    • JavaScript runs one task at a time in order. This is called single-threaded execution.
  5. Asynchronous Code Uses the Event Loop
    • For things like waiting for a button click or fetching data, JavaScript doesn’t pause everything. It uses an event loop to handle tasks later without blocking the page.

What Is the JavaScript Engine?

The JavaScript Engine is a program embedded in your browser that:

  • Converts your human-readable code into machine code
  • Executes that machine code quickly and efficiently
  • Manages memory and performance behind the scenes

Example: Chrome uses V8, which is extremely fast and powers both Chrome and Node.js.


JavaScript Runtime Environment

Your code doesn’t run on its own — it runs inside the JavaScript runtime, which includes:

ComponentRole
JavaScript EngineExecutes your code
Web APIsHandles things like timers, DOM, fetch
Callback QueueHolds async tasks like clicks or responses
Event LoopChecks the queue and runs tasks one by one

💡 Even though JavaScript is single-threaded, it can still do things asynchronously using this system.


How Does the Event Loop Work?

Let’s say you write this:

console.log("Start");

setTimeout(() => {
  console.log("Inside timeout");
}, 1000);

console.log("End");

Here’s what happens:

  1. "Start" is logged immediately.
  2. setTimeout is sent to the Web API to wait 1 second.
  3. "End" is logged.
  4. After 1 second, the function inside setTimeout is added to the callback queue.
  5. The event loop sees the queue is ready and runs "Inside timeout".

🧠 JavaScript didn’t pause or sleep — it scheduled the function for later.


Real-World Analogy: Restaurant Kitchen

Think of JavaScript as a chef in a kitchen:

  • The chef (JavaScript engine) takes one order at a time (single-threaded).
  • If a task takes time (like boiling pasta), the chef hands it to an assistant (Web API).
  • The assistant finishes it and notifies the chef when it’s ready (event loop).
  • Meanwhile, the chef keeps working on other tasks.

Why This Matters

Understanding how JavaScript runs helps you:

  • Write better, non-blocking code
  • Debug problems like functions running “out of order”
  • Work with asynchronous features (like setTimeout, fetch, or event listeners)

Summary

TermMeaning
JavaScript EngineConverts and runs your code (e.g., V8)
Runtime EnvironmentThe full system that runs your code, handles async tasks
Single-threadedOne line of code runs at a time
Event LoopManages async operations in a smooth way
Web APIsBrowser-provided features like setTimeout, DOM, AJAX

Optional Activity

Try This in Your Browser Console:

console.log("One");
setTimeout(() => {
  console.log("Two");
}, 2000);
console.log("Three");

Expected output:

One
Three
Two

This shows the async nature of JavaScript using the event loop!