0
0
Javascriptprogramming~5 mins

Practical closure use cases in Javascript

Choose your learning style9 modes available
Introduction

Closures let functions remember the environment where they were created. This helps keep data safe and create useful tools.

When you want to keep some data private and not let other parts change it directly.
When you need to create a function that remembers some settings or values for later use.
When you want to make a function that generates other functions with specific behavior.
When you want to delay running some code but keep access to variables from before.
When you want to count or track something without using global variables.
Syntax
Javascript
function outer() {
  let secret = 42;
  function inner() {
    console.log(secret);
  }
  return inner;
}
The inner function can access variables from the outer function even after outer finishes.
Returning the inner function creates a closure that keeps the outer variables alive.
Examples
This example shows a counter that remembers its count using a closure.
Javascript
function makeCounter() {
  let count = 0;
  return function() {
    count++;
    return count;
  };
}
const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2
This example creates a greeting function that remembers the name.
Javascript
function greet(name) {
  return function(message) {
    console.log(`${message}, ${name}!`);
  };
}
const greetAlice = greet('Alice');
greetAlice('Hello'); // Hello, Alice!
This example creates a function that multiplies by a fixed number.
Javascript
function makeMultiplier(x) {
  return function(y) {
    return x * y;
  };
}
const double = makeMultiplier(2);
console.log(double(5)); // 10
Sample Program

This program uses closures to keep the bank account balance private. Only the returned methods can change or see the balance.

Javascript
function createBankAccount(initialBalance) {
  let balance = initialBalance;
  return {
    deposit(amount) {
      balance += amount;
      console.log(`Deposited: $${amount}`);
    },
    withdraw(amount) {
      if (amount <= balance) {
        balance -= amount;
        console.log(`Withdrew: $${amount}`);
      } else {
        console.log('Insufficient funds');
      }
    },
    getBalance() {
      return balance;
    }
  };
}

const myAccount = createBankAccount(100);
myAccount.deposit(50);
myAccount.withdraw(30);
console.log(`Balance: $${myAccount.getBalance()}`);
OutputSuccess
Important Notes

Closures help protect data by hiding it inside functions.

Be careful with closures inside loops to avoid unexpected results.

Closures can use more memory because they keep variables alive.

Summary

Closures let functions remember variables from where they were made.

They are useful for data privacy, creating special functions, and keeping state.

Closures are a powerful tool to write cleaner and safer code.