The Fundamental Problem: Computers are Not Smart

The most important thing to remember is that a computer's processor (CPU) doesn't understand JavaScript. It only understands one thing: Machine Code (sequences of 1s and 0s).

Our goal is to translate the human-friendly JavaScript we write into machine-friendly instructions. This translation job is done by the JavaScript Engine.

The JavaScript Engine: A program that reads, translates, and executes JavaScript code. The most famous one is Google's V8, which powers Chrome and Node.js.

The Engine's Two Core Components

To manage our code, the engine sets up two primary areas in memory:

  1. The Memory Heap: A large, unstructured pool of memory. Think of it as a giant warehouse where all the "things" (objects, arrays, and most importantly, functions) from your code are stored.
  2. The Call Stack: A highly organized, temporary workspace. Think of it as a to-do list where you can only add tasks to the top and can only work on the topmost task. It's responsible for managing which function is currently running.

The Two-Phase Process: The Secret to "Hoisting"

The engine does not just read your code from top to bottom and run it. For any piece of code (the global script, a function), it performs a two-phase process.

  1. Creation Phase (Memory Setup): The engine takes a quick first pass through the code. It doesn't execute anything. Its only job is to find all the variable and function declarations and set aside memory for them.
  2. Execution Phase (Doing the Work): After the setup is complete, the engine takes a second pass to actually execute the code: assigning values to variables, calling functions, and running the logic.

This two-phase process is what creates the effect we call hoisting.


A Detailed Walkthrough: From Code to Console

Let's trace the following code step-by-step to see every part of the process.

Our Code Example:

// script.js
var score = 50;
const playerName = "Alex";

function calculateBonus(currentScore) {
    var bonus = currentScore / 10;
    return bonus;
}

var finalScore = score + calculateBonus(score);
console.log(finalScore);

Step 0: The "Before You Run" Phase (Compilation)