JavaScript Interview Question #101

What is a closure in JavaScript?

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

Quick Interview Answer

A closure is created when a function retains access to variables from its lexical scope even after the outer function has finished executing. The inner function keeps a reference to the required surrounding environment rather than receiving a one-time copy of each value.

Detailed Explanation

A closure is created when a function retains access to variables from its lexical scope even after the outer function has finished executing. The inner function keeps a reference to the required surrounding environment rather than receiving a one-time copy of each value.

Closures are widely used for private state, factory functions, callbacks, event handlers, memoization, and module patterns. They are a core JavaScript concept because functions are lexically scoped and can be returned or passed as values.

Code Example

function createCounter() {
    let count = 0;

    return function () {
        count++;
        return count;
    };
}

const counter = createCounter();

console.log(counter()); // 1
console.log(counter()); // 2