Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 1 of 8 · Closures and Callbacks
Interview question

What is a closure in JavaScript? JavaScript में closure क्या है?

Answer

A closure is a function that has access to variables from another function's scope. This is possible because functions in JavaScript form closures around the data they need, and they retain access to outer function variables even after the outer function has returned.

// Simple closure example
function outer() {
    let count = 0; // outer function's variable
    
    function inner() {
        count++; // inner function accesses outer variable
        console.log(count);
    }
    
    return inner;
}

const counter = outer();
counter(); // 1
counter(); // 2
counter(); // 3

// The inner function 'closes over' the count variable
// It retains access to count even after outer() has finished executing

// Practical example: Counter factory
function createCounter() {
    let count = 0;
    
    return {
        increment: () => ++count,
        decrement: () => --count,
        getCount: () => count
    };
}

const myCounter = createCounter();
console.log(myCounter.increment()); // 1
console.log(myCounter.increment()); // 2
console.log(myCounter.decrement()); // 1
console.log(myCounter.getCount());  // 1

// count is private - cannot access directly
console.log(myCounter.count); // undefined

// Another example: Bank account with closures
function createBankAccount(initialBalance) {
    let balance = initialBalance;
    
    return {
        deposit: (amount) => {
            balance += amount;
            return `Balance: $${balance}`;
        },
        withdraw: (amount) => {
            if (amount > balance) {
                return 'Insufficient funds';
            }
            balance -= amount;
            return `Balance: $${balance}`;
        },
        getBalance: () => balance
    };
}

const account = createBankAccount(1000);
console.log(account.deposit(500));   // Balance: $1500
console.log(account.withdraw(200));  // Balance: $1300
console.log(account.getBalance());   // 1300

// Closures in loops - common interview question
const functions = [];

// Without closure (WRONG)
for (var i = 0; i < 3; i++) {
    functions.push(() => console.log(i)); // 'var' is function-scoped
}
functions[0](); // 3 (not 0!)
functions[1](); // 3 (not 1!)
functions[2](); // 3 (not 2!)

// With closure (CORRECT) - using let
const correctFunctions = [];
for (let j = 0; j < 3; j++) {
    correctFunctions.push(() => console.log(j)); // 'let' is block-scoped
}
correctFunctions[0](); // 0
correctFunctions[1](); // 1
correctFunctions[2](); // 2

// Alternative: IIFE to create closure
const iifeFunctions = [];
for (var k = 0; k < 3; k++) {
    iifeFunctions.push((function(value) {
        return () => console.log(value);
    })(k));
}
iifeFunctions[0](); // 0
iifeFunctions[1](); // 1
iifeFunctions[2](); // 2

Interview tip: Explain that closures are created every time a function is created. Mention the practical benefits: data privacy (encapsulation), function factories, and module pattern. The loops example is a classic interview question - explain why 'var' causes the issue and why 'let' solves it.

Closure एक function है जिसके पास दूसरे function के scope के variables access हैं। Functions JavaScript में closures form करते हैं और outer function variables को retain करते हैं भले ही outer function return हो चुका हो।

// Simple closure
function outer() {
    let count = 0; // outer का variable
    
    function inner() {
        count++; // inner इसे access करता है
        console.log(count);
    }
    
    return inner;
}

const counter = outer();
counter(); // 1
counter(); // 2
counter(); // 3

// Counter factory
function createCounter() {
    let count = 0;
    
    return {
        increment: () => ++count,
        decrement: () => --count,
        getCount: () => count
    };
}

const myCounter = createCounter();
console.log(myCounter.increment()); // 1
console.log(myCounter.increment()); // 2
console.log(myCounter.decrement()); // 1

// count private है - direct access नहीं
console.log(myCounter.count); // undefined

// Bank account example
function createBankAccount(initialBalance) {
    let balance = initialBalance;
    
    return {
        deposit: (amount) => {
            balance += amount;
            return `Balance: $${balance}`;
        },
        withdraw: (amount) => {
            if (amount > balance) return 'Insufficient';
            balance -= amount;
            return `Balance: $${balance}`;
        },
        getBalance: () => balance
    };
}

const account = createBankAccount(1000);
console.log(account.deposit(500));   // Balance: $1500

// Loop closure issue
const funcs = [];
for (var i = 0; i < 3; i++) {
    funcs.push(() => console.log(i));
}
funcs[0](); // 3 (गलत!)

// let से solve होता है
const correctFuncs = [];
for (let j = 0; j < 3; j++) {
    correctFuncs.push(() => console.log(j));
}
correctFuncs[0](); // 0 (सही!)

इंटरव्यू टिप: समझाएं closures हर बार create होते हैं जब function create होता है। Practical benefits बताएं: data privacy, function factories, module pattern। Loops का example एक classic interview question है - समझाएं क्यों 'var' से issue आता है और क्यों 'let' solve करता है।

Was this answer clear?