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.
To manage our code, the engine sets up two primary areas in memory:
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.
This two-phase process is what creates the effect we call hoisting.
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);