Skip to content

Closures & Scope

JavaScript

Master closures: lexical scope, capturing variables, and common patterns.

Official Site
01

Overview

A closure is a function plus its lexical environment. Inner functions capture variables from outer scope. Closures enable data privacy, function factories, and partial application. Each closure has its own captured variables.

bash
function counter(){
  let count=0;
  return ()=>++count;
}
const c=counter();
c(); c(); // 2
// Module pattern
const mod=(()=>{let private=1; return {get:()=>private};})();
02

Best Practices

Use closures for data privacy and state encapsulation. Beware of capturing loop variables (use let or IIFE). Closures retain memory (avoid in hot paths). Use closures for currying and partial application. Module pattern uses closures for private state.

Ready to try Closures & Scope?

Visit the official site for the latest version and full documentation.

Visit Closures & Scope