Day 15 of 100: Closures — Counters, Factories, and the var Loop Bug
Day 15 of 100 — 100 Days of Playwright with TypeScript Challenge. Phase: JavaScript Fundamentals. JavaScript (Days 1-33) → TypeScript (Days 34-63) → Playwright (Days 64-96) → AI Framework Capstone (Days 97-100).
🎭 Want to master this with real projects? Join the Playwright Automation Mastery course at The Testing Academy.
Closures: functions remember the scope they were created in. Powers counters, factories — and one classic loop bug.
Contents
The Concept
function makeCounter() {
let count = 0; // private to the closure
return function() {
count++;
return count;
};
}
const counter = makeCounter();
counter(); // 1
counter(); // 2 — count persists between calls
🚀 Level Up Your Playwright
From locators to CI pipelines — build a production-grade Playwright + TypeScript framework step by step.
QA Use: Unique ID Generator
function makeIdGenerator(prefix) {
let n = 0;
return () => `${prefix}-${++n}-${Date.now()}`;
}
const userId = makeIdGenerator('user');
userId(); // user-1-17...
userId(); // user-2-17...
// Unique test data per call — no collisions in parallel runs
The Classic var Loop Bug
// BUG: var shares one variable across iterations
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log('var:', i), 10);
}
// prints 3, 3, 3
// FIX: let creates a fresh binding per iteration
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log('let:', j), 10);
}
// prints 0, 1, 2
Tomorrow (Day 16): Scope and hoisting — where variables live.
🎓 Master Playwright End to End
Join hundreds of SDETs building real automation frameworks. Lifetime access, hands-on projects, and a job-ready portfolio.
