🎬 The JS House — Understanding Scope
Global (Main Hall)
var username = "Alex"
Function Scope (Kitchen)
var item = "Batter"
Block Scope (Bedroom)
let secret = "Chocolate"
Rule: children can see parents, parents cannot see children. GlobalFunctionBlock (let/const)
⚡ Two Phases — Hoisting Visual
Declarations rise
Assignments run
Assignments run
Compilation (Memory): var a; • function greet(){...}
Execution (Run time): a = 2; • greet();
Declarations are “lifted” to the top of their scope before execution begins. Function declarations hoist with bodies; variables hoist as names (initially undefined).
🧪 Practice Playground (Sandboxed)
Console (isolated iframe)
📝 Pocket Rules
- Scope: where a variable is visible — Global, Function (
var), Block (let/const). - Hoisting: declarations first, then execution. Variables hoist as names; value comes later.
- Functions first: function declarations hoist above
var. - Function expressions behave like assignments; only the variable name hoists.
- TDZ:
let/constexist but are inaccessible before their line.
🧠 Quick Quiz
What is printed?
console.log(a);
var a = 10;
Which is true?
Output?
foo(); // ?
var foo;
function foo(){ console.log(1); }
foo = function(){ console.log(2); };