GoalStop being surprised by JavaScript. Execution context, closures (the real mechanism), var vs let, this binding, and garbage collection.
Lessons
Execution Context & Hoisting
Every time code runs, the engine creates an Execution Context in two phases:
var declarations are reserved and set to undefined
Function declarations are stored fully in memory
this is set
Phase 2 — Execution: lines run, values are assigned.
js
console.log(x); // undefined — var was hoisted
sayHi(); // "hi" — function declaration fully hoisted
console.log(y); // ❌ ReferenceError — let has a Temporal Dead Zone
var x = 5;
function sayHi() { console.log("hi"); }
let y = 10;
TDZ (Temporal Dead Zone): let/const are hoisted but marked off-limits until their line runs. This is a safety feature.
Scope Chain & Lexical Scope
Scope is determined by where you write code (lexical), not where you call it.
Lookups go outward along the scope chain — never inward.
js
const a = 1;
function outer() {
const b = 2;
function inner() {
const c = 3;
console.log(a, b, c); // all visible — looks up the chain
}
// outer CANNOT see c
}
The scope chain is built at write time, permanently. Calling inner from anywhere in the world, it still looks up into outer, then global.
Closures — the real mechanism
When a function is created, it stores a hidden link to the scope it was born in. Even after that scope's function returns, the link keeps the scope alive in the Heap.
js
function makeCounter() {
let count = 0; // lives in makeCounter's scope
return () => ++count; // inner function keeps a link here
}
const c = makeCounter(); // makeCounter finished — but count is NOT freed
c(); // 1
c(); // 2
The closure is that kept-alive scope. It's not magic — it's the GC rule: *reachable = not freed*. The returned function is reachable → it holds a link to the scope → the scope is reachable → count survives.
Memory leak consequence: if a closure (or event listener) accidentally holds a reference to something large (DOM node, huge array), that thing can never be freed as long as the closure lives.
var vs let — the loop trap
var is function-scoped: ONE binding for the whole loop.
let is block-scoped: a fresh binding per iteration.
js
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// prints: 3 3 3 — all three closures share ONE i
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// prints: 0 1 2 — each closure captures its OWN i
This single difference explains the most common beginner async bug.
this — four rules
this is set by how a function is called, not where it's written.
js
// 1. Regular call → undefined (strict) or global
function f() { console.log(this); }
f();
// 2. Method call → the object before the dot
obj.greet(); // this = obj
// 3. Explicit binding
f.call({ name: "Ali" }); // this = {name: "Ali"}
// 4. Arrow functions → inherit this from enclosing scope (NO own this)
const obj = {
name: "Ali",
greet() {
setTimeout(() => console.log(this.name), 0); // "Ali" ✅
}
};
Arrow functions don't have their own this — they look it up lexically. An object literal is not a scope, so const arrow = () => this at the top level gets the module/global this, not the object.
Challenges4
Write working code. Run to see output. Check to grade.
CH1
Build a closure counter
Warm-up
Write makeCounter(start) that returns a function. Each call increments and returns the count, starting at start.
This prints 3 3 3. Fix it to print 0 1 2 without changing the setTimeout logic.
You may change var to let, OR use an IIFE — explain your choice in a comment.
JavaScript
CH3
this — method extraction trap
Hard
Predict the output of each console.log. Then write your predictions as three separate console.log calls logging the correct values.
This has a memory leak. The huge array is NEVER freed even though the returned function doesn't use it.
1. Run it and log the result to confirm it works.
2. Fix the leak so bigData can be garbage-collected.
3. Add a comment explaining WHY the leak happened in GC terms.
js
function setup() {
const bigData = new Array(1_000_000).fill("x");
return function handler() {
return "done";
};
}
const fn = setup();