JS Closures
function outer() {
let outerVariable = value;
return function inner() {
return outerVariable;
};
}
const closure = outer();
What Is a Closure?
A closure happens when a function remembers variables from its outer scope. The inner function can use those variables later.
This is possible because JavaScript functions keep a live reference to their enclosing scope, not a snapshot of it, so the variables persist as long as the closure does.
उदाहरण: What Is a Closure?
function outer() {
const message = "Hello";
function inner() {
console.log(message); // remembers outer's variable
}
return inner;
}
const greet = outer();
greet();
Private Data
Closures can keep data private. Code outside the closure cannot directly access the hidden variable.
This is a common way to implement things like a counter that increments correctly even though no other code can read or overwrite its internal count directly.
उदाहरण: Private Data
function makeCounter() {
let count = 0; // private, not accessible outside
return function () {
count++;
return count;
};
}
const counter = makeCounter();
console.log(counter());
console.log(counter());
Closures With Parameters
Each call can create a separate closure. The stored values do not have to be shared. Because each function call gets its own execution context, a factory function that returns a closure produces independent, non-interfering instances.
उदाहरण: Closures With Parameters
function makeMultiplier(factor) {
return (n) => n * factor;
}
const double = makeMultiplier(2);
const triple = makeMultiplier(3);
console.log(double(5), triple(5)); // independent closures
Practical Use
Closures are useful for counters, factories, and functions that need remembered settings.
A closure that captures a database connection or API key, for instance, lets you expose a clean function API without re-passing that configuration on every call.
उदाहरण: Practical Use
// Define the function `createApiClient` taking `apiKey`
// Define the function `createApiClient` taking `apiKey`
function createApiClient(apiKey) {
// Return `function fetchData() {` from this function
// Return `function fetchData() {` from this function
return function fetchData() {
// Print `"Using key:", apiKey` to the console
// Print `"Using key:", apiKey` to the console
console.log("Using key:", apiKey);
};
}
// Declare the constant `client`, set to `createApiClient("secret123")`
// Declare the constant `client`, set to `createApiClient("secret123")`
const client = createApiClient("secret123");
// Call `client()`
// Call `client()`
client();
Practice
Try creating closures that remember a number or a name. Try writing a makeCounter() function that returns increment/decrement functions sharing one hidden counter variable.
उदाहरण: Practice
// Define the function `makeCounter` with no parameters
// Define the function `makeCounter` with no parameters
function makeCounter() {
// Declare the variable `count`, set to `0`
// Declare the variable `count`, set to `0`
let count = 0;
// Return `{` from this function
// Return `{` from this function
return {
increment: () => ++count,
decrement: () => --count,
};
}
// Declare the constant `c`, set to `makeCounter()`
// Declare the constant `c`, set to `makeCounter()`
const c = makeCounter();
// Print `c.increment(), c.increment(), c.decrement()` to the console
// Print `c.increment(), c.increment(), c.decrement()` to the console
console.log(c.increment(), c.increment(), c.decrement());
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: