JavaScript and TypeScript course Β· Module 2: Functions, Arrays and Objects
Closures and Lexical Scope
In this lesson7
In Jurassic Park every paddock has a fence and every lab has a door with an access code. Scope in JavaScript works the same way: it is an invisible fence that decides which variables are available in a given place in the code. There is also a problem: how do you build a sighting counter that no other system can reset by mistake? A global variable is open to everyone. The answer is closures, a dinosaur that remembers the PIN to its paddock long after the keeper has gone.
Lexical Scope
JavaScript uses lexical scope: access to variables depends on where the code was written, not on where it was called. Picture the park map: each paddock (function) sees the main road (global scope) and its own territory, but it cannot see inside other paddocks.
// Global scope - the main road of Jurassic Park
const parkName = "Jurassic Park";
function enclosureA() {
// Scope of enclosureA - Paddock A
const dinosaurA = "Tyrannosaurus Rex";
console.log(parkName); // "Jurassic Park" - sees the global scope
console.log(dinosaurA); // "Tyrannosaurus Rex" - sees its own scope
function innerFence() {
// Nested scope - the inner fence
const babyDino = "Baby Rex";
console.log(parkName); // "Jurassic Park" - sees the global scope
console.log(dinosaurA); // "Tyrannosaurus Rex" - sees the parent scope
console.log(babyDino); // "Baby Rex" - sees its own scope
}
innerFence();
// console.log(babyDino); // ERROR! Cannot see inside innerFence
}
function enclosureB() {
// Scope of enclosureB - Paddock B
const dinosaurB = "Triceratops";
console.log(parkName); // "Jurassic Park" - sees the global scope
// console.log(dinosaurA); // ERROR! Cannot see inside enclosureA
}The rule is simple: an inner function sees the variables of the outer function, but not the other way round. A dinosaur in the inner paddock can see out through the fence, while a keeper outside cannot look through the double walls. That is why innerFence reads dinosaurA without receiving it as an argument, and enclosureB has no access to it.
What Is a Closure?
A closure is a function that "remembers" the variables from the scope where it was created, even after that scope has finished running. See it in a sighting tracker:
function createDinoTracker(species) {
// The "species" variable lives in the scope of createDinoTracker
let sightings = 0;
// This inner function creates a CLOSURE
// - it "remembers" species and sightings, even after createDinoTracker ends
return function reportSighting(location) {
sightings++;
console.log(species + " seen at: " + location + " (sighting #" + sightings + ")");
};
}
// createDinoTracker has finished, but the returned function REMEMBERS the variables
const trackRex = createDinoTracker("T-Rex");
const trackRaptor = createDinoTracker("Velociraptor");
trackRex("Sector A"); // "T-Rex seen at: Sector A (sighting #1)"
trackRex("Sector B"); // "T-Rex seen at: Sector B (sighting #2)"
trackRaptor("Laboratory"); // "Velociraptor seen at: Laboratory (sighting #1)"
// Each closure has its OWN copy of the variables!
// trackRex has its own sightings = 2, trackRaptor has its own sightings = 1Each call to createDinoTracker creates a new scope, so the counters of the two trackers are independent. Nobody outside can change sightings, because the variable is not visible outside the function. The mechanism follows five steps:
- You define an outer function with local variables.
- Inside it, you define an inner function that uses them.
- The outer function returns the inner function with
return. - You call the outer function and store the result in a variable.
- You call the returned function, and it still has access to the outer variables.
Practical Uses of Closures
Data Privacy (Encapsulation)
Closures let you create private variables that nobody outside can reach. Like the park security system, where the access codes are locked away in a sealed cabinet:
function createSecuritySystem(enclosureName) {
// These variables are PRIVATE - inaccessible from outside
let accessCode = Math.floor(Math.random() * 9000) + 1000;
let isLocked = true;
const accessLog = [];
return {
unlock(code) {
if (code === accessCode) {
isLocked = false;
accessLog.push("Unlocked: " + new Date().toLocaleTimeString());
console.log(enclosureName + " - fence DISABLED");
} else {
accessLog.push("Failed attempt: " + new Date().toLocaleTimeString());
console.log(enclosureName + " - WRONG CODE!");
}
},
lock() {
isLocked = true;
accessLog.push("Locked: " + new Date().toLocaleTimeString());
console.log(enclosureName + " - fence ENABLED");
},
getStatus() {
return isLocked ? "LOCKED" : "OPEN";
},
getLog() {
return [...accessLog]; // Returns a copy, not the original
}
};
}
const rexSecurity = createSecuritySystem("T-Rex Paddock");
// There is no way to read accessCode directly!
// rexSecurity.accessCode β undefined (private variable)The returned object has only four methods. accessCode, isLocked and accessLog are not its properties but variables from the closure, so only those methods can change them. getLog() hands out a copy of the array, so clearing the result will not touch the real log.
Function Factories
Closures make it possible to build factories, functions that produce other functions with built-in configuration. Like a genetics lab that creates dinosaurs from specific DNA:
function createDinoFilter(property, value) {
// The closure "remembers" property and value
return function(dinosaur) {
return dinosaur[property] === value;
};
}
const isCarnivore = createDinoFilter("diet", "carnivore");
const isHerbivore = createDinoFilter("diet", "herbivore");
const isSectorA = createDinoFilter("sector", "A");
const dinosaurs = [
{ name: "Rex", diet: "carnivore", sector: "A" },
{ name: "Tricia", diet: "herbivore", sector: "B" },
{ name: "Blue", diet: "carnivore", sector: "C" }
];
console.log(dinosaurs.filter(isCarnivore)); // Rex, Blue
console.log(dinosaurs.filter(isHerbivore)); // Tricia
console.log(dinosaurs.filter(isSectorA)); // RexThree filters came out of one factory, and each remembers its own property and value pair. The smallest factory fits in three lines:
function createMultiplier(factor) {
return n => n * factor;
}
const double = createMultiplier(2);
const triple = createMultiplier(3);
console.log(double(5)); // 10
console.log(triple(4)); // 12The arrow function remembers factor, so double and triple share the same code but have different configurations.
IIFE - Immediately Invoked Function Expressions
An IIFE (immediately invoked function expression) is a function that is defined and run right away. It is a one-time security protocol: it starts, does its job and disappears without leaving traces in the global scope.
// IIFE syntax
(function() {
const secretData = "Location of the hidden lab";
console.log("IIFE executed! Data: " + secretData);
})();
// secretData does not exist in the global scope!
// Arrow IIFE
(() => {
const emergencyProtocol = "Evacuate sector 7";
console.log("Emergency protocol activated: " + emergencyProtocol);
})();
// IIFE with parameters
const dinoReport = (function(parkData) {
const processed = parkData.map(d => d.toUpperCase());
return processed.join(", ");
})(["rex", "raptor", "triceratops"]);
console.log(dinoReport); // "REX, RAPTOR, TRICERATOPS"The structure is always the same: an opening parenthesis, function(), the body { /* code */ }, a closing parenthesis and (), which calls the function. The parentheses around the function turn it into an expression; without them the engine reports a syntax error. When an IIFE returns an object with methods, you get a module with private state:
const visitorCounter = (function() {
let count = 0; // private state of the module
return {
increment() { return ++count; },
getValue() { return count; }
};
})();
visitorCounter.increment(); // 1
visitorCounter.increment(); // 2
console.log(visitorCounter.getValue()); // 2IIFEs were very popular before ES6, when var had no block scope. They still isolate code today, but in a new project I recommend ES modules with import and export, and it is worth recognizing IIFEs in older code.
Hoisting - var vs let/const
Hoisting is the mechanism in which variable and function declarations are "moved" to the top of their scope. Each keyword behaves differently, though:
// var - hoisted with the value undefined
console.log(dinoVar); // undefined (not an error!)
var dinoVar = "Stegosaurus";
console.log(dinoVar); // "Stegosaurus"
// let/const - hoisted, but with a "Temporal Dead Zone" (TDZ)
// console.log(dinoLet); // ReferenceError! The variable is in the TDZ
let dinoLet = "Ankylosaurus";
console.log(dinoLet); // "Ankylosaurus"
// const - same as let, plus it requires immediate initialization
// console.log(dinoConst); // ReferenceError! TDZ
const dinoConst = "Brachiosaurus";A let variable exists from the start of the block, but until its declaration line it sits in a no-entry zone, so reading it ends with a ReferenceError, not with undefined or null.
var vs let in Loops - the Classic Trap
This is one of the most famous JavaScript problems, where closures and var produce unexpected results:
// The problem with var - all closures share the same variable
for (var i = 0; i < 3; i++) {
setTimeout(function() {
console.log("var: Dinosaur #" + i); // Always "Dinosaur #3"!
}, 100);
}
// The fix with let - each iteration gets its own copy
for (let j = 0; j < 3; j++) {
setTimeout(function() {
console.log("let: Dinosaur #" + j); // 0, 1, 2 - correct!
}, 100);
}Why does var fail? It has function scope, so all three closures refer to one variable i, which equals 3 after the loop. let has block scope, and each iteration creates a new variable j. Before let existed, developers used an IIFE that freezes the current value:
// The older fix: an IIFE captures the current value
for (var k = 0; k < 3; k++) {
(function(captured) {
setTimeout(function() {
console.log("IIFE: Dinosaur #" + captured); // 0, 1, 2
}, 100);
})(k);
}It works, but let does the same without an extra function, so choose let.
Summary
| Concept | Jurassic Park Analogy |
|---|---|
| Global scope | The main park road - visible from every paddock |
| Function scope | A dinosaur's paddock - it sees out, but nobody sees in |
| Closure | A dinosaur remembers the park layout even after the fences are rebuilt |
| Private variables | The fence PIN code - hidden inside a sealed system |
| IIFE | A one-time security protocol - run and forget |
| Hoisting var | A dinosaur that appears on the list before it hatches |
| TDZ (let/const) | A no-entry zone until the paddock officially opens |
Closures will come back in the module on asynchronous code, because every callback passed to setTimeout or a promise relies on a closure.
Practice
The sandbox contains lexical scope, the sighting tracker and a security system with a private log. Call the trackers a few times and check that each one counts separately.
Code for this lesson: index.js
// Closures and lexical scope - Jurassic Park
console.log("=== CLOSURES IN JURASSIC PARK ===\n");
// ================================================
// 1. LEXICAL SCOPE - park enclosures
// ================================================
console.log("--- 1. Lexical scope ---");
const parkName = "Jurassic Park"; // Global scope
function enclosureA() {
const dinosaurA = "Tyrannosaurus Rex"; // enclosureA scope
function innerFence() {
const babyDino = "Baby Rex"; // innerFence scope
// Sees EVERYTHING: its own variables + the parent's + global ones
console.log("innerFence sees: " + parkName + ", " + dinosaurA + ", " + babyDino);
}
innerFence();
// console.log(babyDino); // ERROR! Cannot see inside innerFence
console.log("enclosureA sees: " + parkName + ", " + dinosaurA);
}
enclosureA();
// ================================================
// 2. CLOSURE - the dinosaur remembers its environment
// ================================================
console.log("\n--- 2. Closure - dinosaur tracker ---");
function createDinoTracker(species) {
let sightings = 0; // This variable lives in the closure!
return function reportSighting(location) {
sightings++; // The closure remembers and modifies sightings
console.log(species + " sighted at: " + location + " (observation #" + sightings + ")");
};
}
const trackRex = createDinoTracker("T-Rex");
const trackRaptor = createDinoTracker("Velociraptor");
trackRex("Sector A");
trackRex("Sector B");
trackRaptor("Laboratory");
trackRex("Sector C");
// Each tracker has its OWN copy of the sightings variable!
// ================================================
// 3. DATA PRIVACY - security system
// ================================================
console.log("\n--- 3. Private variables (encapsulation) ---");
function createSecuritySystem(enclosureName) {
let isLocked = true; // PRIVATE variable
const log = [];
return {
unlock() {
isLocked = false;
log.push("Unlocked at " + new Date().toLocaleTimeString());
console.log(enclosureName + " - fence DISABLED");
},
lock() {
isLocked = true;
log.push("Locked at " + new Date().toLocaleTimeString());
console.log(enclosureName + " - fence ENABLED");
},
getStatus() {
return enclosureName + ": " + (isLocked ? "LOCKED" : "OPEN");
},
getLog() { return [...log]; }
};
}
const rexSecurity = createSecuritySystem("T-Rex Paddock");
console.log(rexSecurity.getStatus());
rexSecurity.unlock();
console.log(rexSecurity.getStatus());
rexSecurity.lock();
console.log("Log:", rexSecurity.getLog());
// rexSecurity.isLocked -> undefined (private!)
// ================================================
// 4. FACTORY FUNCTION
// ================================================
console.log("\n--- 4. Factory function ---");
function createDinoFilter(property, value) {
return function(dinosaur) {
return dinosaur[property] === value;
};
}
const dinosaurs = [
{ name: "Rex", diet: "carnivore", sector: "A" },
{ name: "Tricia", diet: "herbivore", sector: "B" },
{ name: "Blue", diet: "carnivore", sector: "C" },
{ name: "Steggy", diet: "herbivore", sector: "A" }
];
const isCarnivore = createDinoFilter("diet", "carnivore");
const isSectorA = createDinoFilter("sector", "A");
console.log("Carnivores:", dinosaurs.filter(isCarnivore).map(d => d.name));
console.log("Sector A:", dinosaurs.filter(isSectorA).map(d => d.name));
// ================================================
// 5. IIFE - a one-time protocol
// ================================================
console.log("\n--- 5. IIFE ---");
const emergencyReport = (function(dinos) {
const carnivores = dinos.filter(d => d.diet === "carnivore");
const herbivores = dinos.filter(d => d.diet === "herbivore");
return "Report: " + carnivores.length + " carnivores, " + herbivores.length + " herbivores";
})(dinosaurs);
console.log(emergencyReport);
// ================================================
// 6. HOISTING - var vs let
// ================================================
console.log("\n--- 6. Hoisting ---");
// var - hoisting with undefined
console.log("var before declaration:", typeof dinoVar); // undefined
var dinoVar = "Stegosaurus";
console.log("var after declaration:", dinoVar);
// let - Temporal Dead Zone
// console.log(dinoLet); // ReferenceError!
let dinoLet = "Ankylosaurus";
console.log("let after declaration:", dinoLet);
// var vs let in a loop
console.log("\nLoop with let:");
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log(" let: Dinosaur #" + j), 10);
}Remember: a closure is a dinosaur that remembers its paddock, a function that carries the variables from the place where it was born.
Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What will we see in the console after running the following code? function outer() { const x = 10; function inner() { console.log(x); } inner(); } outer();
2. What is a closure in JavaScript?
3. What will happen when we try to use a variable declared with let BEFORE its declaration? console.log(dinoName); let dinoName = "Rex";
Hands-on tasks in the game
- Code editor
Write a function createDinoTracker(species) that keeps a private counter sightings and an array history in a closure and returns an object with the methods: reportSighting(location) (increases the counter and adds the location to the history), getSightings() (returns the number of sightings) and getHistory() (returns a copy of the history). Also write createEnclosure(name, maxCapacity) with a private array residents and the methods: addDinosaur(dinoName) (adds the dinosaur and returns true, or returns false when there is no room), removeDinosaur(dinoName), getPopulation() (returns a copy of the array) and getStatus() (returns the text 'name: X/maxCapacity', e.g. 'Paddock T-Rex: 1/2').
- Vertical ordering
Arrange the steps of creating and using a closure in JavaScript:
- Click in order
Build a correct IIFE (Immediately Invoked Function Expression) by clicking elements in the right order:
- Code editor
Write a factory createFilter(property, value) that returns a function checking whether object[property] === value, and a factory createWeightConverter(multiplier) that returns a function multiplying a weight in kilograms by multiplier. Then use an IIFE to create a counter dinoCounter with a private variable count and the methods increment(), decrement() and getValue().