JavaScript Interview Question #102

What are practical uses of closures?

Closures, Prototypes, Classes & Advanced Functions Mid-Level Intermediate

Quick Interview Answer

Closures are useful whenever a function needs to remember state from the environment in which it was created. Common examples include counters, configuration factories, encapsulated state, partially configured functions, event handlers, and caching.

Detailed Explanation

Closures are useful whenever a function needs to remember state from the environment in which it was created. Common examples include counters, configuration factories, encapsulated state, partially configured functions, event handlers, and caching.

A closure can provide controlled access to data without exposing that data as a global variable. However, retained references also keep required objects alive, so unnecessarily large captured state can increase memory usage.

Code Example

function createDiscount(rate) {
    return price => price * (1 - rate);
}

const tenPercentOff = createDiscount(0.10);

console.log(tenPercentOff(100)); // 90
console.log(tenPercentOff(250)); // 225