JavaScript Closures

Beginner
6 min read
Updated: Nov 2026
3 examples

Definition and Usage

A closure is a function that remembers the variables from the scope where it was created, even after that outer function has finished running.

JavaScript Syntax

JavaScript
function makeCounter() {
  let count = 0;
  return function () {
    count += 1;
    return count;
  };
}

const next = makeCounter();
console.log(next());
console.log(next());
Try it Editor

How It Works

  1. Outer scope. makeCounter creates a local count.
  2. Return inner. The returned function closes over count.
  3. Still alive. Each call updates the same count, even though makeCounter already returned.

Examples

Example 1 — Private State

Hide a value so only the returned functions can change it.

JavaScript
function bank(start) {
  let balance = start;
  return {
    deposit(n) { balance += n; return balance; },
    get() { return balance; }
  };
}
const acct = bank(100);
console.log(acct.deposit(40));
console.log(acct.get());
Try it Editor

How It Works

  1. Hidden balance. Nothing outside can touch balance directly.
  2. Methods close over it. deposit and get share the same variable.

Example 2 — Greeter Factory

Build specialized functions from a shared prefix.

JavaScript
function greeter(prefix) {
  return (name) => prefix + ", " + name + "!";
}
const hi = greeter("Hi");
console.log(hi("Ada"));
Try it Editor

How It Works

  1. Capture prefix. The arrow remembers prefix.
  2. Reuse. Call hi with any name.

Example 3 — Closure in a Loop

Each function keeps its own copy of the loop variable when you use let.

JavaScript
const fns = [];
for (let i = 0; i < 3; i++) {
  fns.push(() => i);
}
console.log(fns.map((f) => f()).join(", "));
Try it Editor

How It Works

  1. let per iteration. Each arrow closes over a different i.
  2. Call later. Mapping the functions returns 0, 1, 2.

Frequently Asked Questions

A function bundled with the variables it can access from its outer scopes.

They create private state, factories, and callbacks that remember context.

They keep referenced outer variables alive. That is intentional; release references when you no longer need the function.

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful