DEV Community

Cover image for JavaScript Closures Explained in Simple Terms
Homayoun Mohammadi
Homayoun Mohammadi

Posted on

JavaScript Closures Explained in Simple Terms

Closures are one of the most important concepts in JavaScript, and understanding them makes you a stronger developer.

What Is a Closure?

A closure is:

A function that remembers and can access variables from its outer function, even after that outer function has finished running.

Think of it like a function carrying a backpack of variables wherever it goes.

Closures Explained With an ATM Example

This is one of the easiest ways to understand closures:

function createBankAccount(initialBalance) {
  let balance = initialBalance; // private money in the "vault"

  return function ATM(withdrawalAmount) {
    if (withdrawalAmount <= balance) {
      balance -= withdrawalAmount;
      console.log(`Withdrawn: $${withdrawalAmount}. Remaining: $${balance}`);
      return withdrawalAmount;
    } else {
      console.log("Insufficient funds!");
      return 0;
    }
  };
}

const myATM = createBankAccount(1000);

myATM(100); // Withdrawn: $100. Remaining: $900
myATM(500); // Withdrawn: $500. Remaining: $400
myATM(450); // Insufficient funds!
Enter fullscreen mode Exit fullscreen mode

What’s happening here?

  1. createBankAccount(1000) sets up the vault (balance)
  2. The returned ATM() function remembers balance
  3. Even when the outer function is done, ATM() still has access to it
  4. That “memory” is the closure in action

How Closures Work

How Closures Work

The outer function creates some variables

The inner function uses them

When the outer function finishes, the variables normally disappear

But if the inner function still needs them, they stay alive

This “saved scope” is called a closure

Closures give a function memory.

Why Closures Are Useful?

Closures appear everywhere in JavaScript. Here are three common uses:

1. Private Variables (Data Privacy)

Closures let you hide data so no one can access it directly.

function createCounter() {
  let count = 0;

  return {
    increment: () => ++count,
    decrement: () => --count,
    getValue: () => count
  };
}

const counter = createCounter();

console.log(counter.getValue()); // 0
counter.increment();
counter.increment();
console.log(counter.getValue()); // 2
Enter fullscreen mode Exit fullscreen mode

The variable count cannot be changed from outside — it's protected.

2. Function Factories (Preset Functions)

You can create functions that remember preset values.

function createMultiplier(multiplyBy) {
  return function(number) {
    return number * multiplyBy;
  };
}

const double = createMultiplier(2);
const triple = createMultiplier(3);

console.log(double(5)); // 10
console.log(triple(5)); // 15
Enter fullscreen mode Exit fullscreen mode

Each multiplier function remembers its own value.

3. Event Handlers (UI Programming)

Each function remembers its loop index or state.

function setupButtons() {
  const buttons = document.querySelectorAll('button');

  for (let i = 0; i < buttons.length; i++) {
    buttons[i].addEventListener('click', () => {
      console.log(`Button ${i + 1} clicked!`);
    });
  }
}
Enter fullscreen mode Exit fullscreen mode

Each click handler remembers its own i.

Closures in One Sentence

A closure is a function that keeps access to variables from the outer scope, even after that outer scope has finished.

Final Summary

  • Closures let functions remember values
  • They keep variables alive & protected
  • They are used in counters, event handlers, callbacks, modules, and more
  • Closures are everywhere in JavaScript once you start noticing them
  • They are essential for writing clean, powerful, and modern JavaScript

Top comments (9)

Collapse
 
maame-codes profile image
Maame Afua A. P. Fordjour

That 'backpack' analogy for closures is genius! It’s the first time I’ve actually visualized what’s happening with the lexical environment in a way that sticks. The ATM example was a perfect follow-up to show why we'd want to use them for data privacy. Thanks for making a tricky concept feel so approachable!

Collapse
 
homayounmmdy profile image
Homayoun Mohammadi • Edited

Thanks so much! 😊

I'm glad the "backpack" analogy and ATM example made closures click for you , that’s exactly what I hoped!
Happy coding! 💡

Collapse
 
maame-codes profile image
Maame Afua A. P. Fordjour

You’re welcome !

Collapse
 
maya_rodriguez_09s profile image
Maya Rodriguez

thanks for sharing

Collapse
 
homayounmmdy profile image
Homayoun Mohammadi

🙏

Collapse
 
maya_rodriguez_09s profile image
Maya Rodriguez

This is the clearest explanation of closures I’ve ever seen finally get it!

Collapse
 
homayounmmdy profile image
Homayoun Mohammadi

So glad it clicked!

Collapse
 
tomas_2cbc42 profile image
Tomas

explain well

Collapse
 
homayounmmdy profile image
Homayoun Mohammadi

thanks