Var Hoisting: Declaration vs Initialization
What you'll learn: How JavaScript separates the declaration and initialization of var variables during hoisting.
The Split Personality of Var
When JavaScript hoists a var declaration, it does something interesting: it splits the declaration from the initialization. The variable name gets hoisted to the top of its scope, but the actual value assignment stays where you wrote it.
Think of it like reserving a parking spot before your car arrives. The spot (declaration) is ready at the beginning, but it's empty (undefined) until your car (the value) actually gets there.
How It Works
When you write:
console.log(myVar); // undefined (not an error!)
var myVar = 10;
console.log(myVar); // 10
JavaScript internally reorganizes it like this:
var myVar; // Declaration hoisted
console.log(myVar); // undefined
myVar = 10; // Assignment stays in place
console.log(myVar); // 10
The declaration (var myVar) moves to the top and is automatically initialized to undefined. The assignment (= 10) remains exactly where you wrote it.
Why Undefined, Not an Error?
Because the variable is declared (hoisted), JavaScript knows it exists—it just doesn't have a value yet. This is why accessing a var variable before its line of code gives you undefined instead of throwing a ReferenceError.
console.log(score); // undefined (declared but not initialized)
var score = 100;
Key Takeaway: var declarations are hoisted to the top of their scope and initialized to undefined, while the actual value assignment stays where you wrote it—allowing you to access the variable before its assignment line (though it will be undefined).