Higher-Order Functions & Closures

๐Ÿ”ด Advanced

๐Ÿ“– Definition

  • Callback Function: A function passed as an argument into another function to be executed later.
  • Higher-Order Function (HOF): A function that receives another function as an argument, or returns a function.
  • Closure: An inner function's ability to retain access to variables in its outer lexical scope even after the outer function has finished execution.

๐Ÿ‡ฎ๐Ÿ‡ณ Hindi

Closure tab banta hai jab ek inner function apne outer function ke variables ko remember rakhta hai, chahe outer function execute hoke finish ho chuka ho. Closure ka primary use data privacy (private variables) aur function factories banane ke liye hota hai.

๐Ÿšฉ Marathi

Closure mhanje aatil (inner) function la baherchya (outer) function mhadhil variables aathvati rahtat, outer function sampaalyanantar hi. Private variables tayar karnya sathi closure cha wapar kela jato.

๐Ÿง  Lexical Scope & Closure Mechanics

When a function is declared inside an outer function, it creates a binding to its surrounding Lexical Environment.

function outerFunction(outerVariable) {

return function innerFunction(innerVariable) {

console.log(Outer: ${outerVariable}, Inner: ${innerVariable});

};

}

const newFunction = outerFunction("INSIDE_CLOSURE");

// outerFunction has returned, but newFunction retains access to outerVariable!

newFunction("CALL_TIME_VALUE");

๐Ÿ’ก Complete Example 1: Private Encapsulated State

function createBankAccount(initialBalance) {

let balance = initialBalance; // Private variable hidden inside closure scope

return {

deposit(amount) {

if (amount > 0) {

balance += amount;

return Deposited โ‚น${amount}. Current Balance: โ‚น${balance};

}

},

withdraw(amount) {

if (amount <= balance) {

balance -= amount;

return Withdrew โ‚น${amount}. Remaining Balance: โ‚น${balance};

}

return "Insufficient funds!";

},

getBalance() {

return Current Balance: โ‚น${balance};

}

};

}

const myAccount = createBankAccount(5000);

console.log(myAccount.deposit(1500));

console.log(myAccount.withdraw(2000));

console.log(myAccount.getBalance());

// console.log(myAccount.balance); // undefined! Cannot be accessed or tampered directly.

๐Ÿ’ก Complete Example 2: Function Factory

function multiplier(factor) {

return (number) => number * factor;

}

const double = multiplier(2);

const triple = multiplier(3);

console.log("Double 5:", double(5)); // 10

console.log("Triple 5:", triple(5)); // 15

๐Ÿ‘€ Output

Deposited โ‚น1500. Current Balance: โ‚น6500

Withdrew โ‚น2000. Remaining Balance: โ‚น4500

Current Balance: โ‚น4500

Double 5: 10

Triple 5: 15

๐Ÿงช Try It Yourself

1. Create a function createCounter() that returns a function that increments and returns a private count variable starting from 0.

2. Test two independent counter instances to verify they maintain separate isolated states.

โš ๏ธ Common Mistakes

  • Misunderstanding that closures capture variable references, not snapshots of static values.
  • Creating unnecessary closures inside large loops which can increase memory usage if not cleaned up.

๐ŸŒ Real-World Usage

Data encapsulation (emulating private fields before native #field syntax), debouncing/throttling event listeners, currying functions, and maintaining state in React hooks like useState.

๐Ÿ’ก Remember

Closure = A function + its lexical environment reference.

๐Ÿงญ Navigation

โ† JS Home | โ† Previous: Array Methods | Next: Promises & Async/Await โ†’