惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园_首页
GbyAI
GbyAI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Apple Machine Learning Research
Apple Machine Learning Research
大猫的无限游戏
大猫的无限游戏
阮一峰的网络日志
阮一峰的网络日志
Last Week in AI
Last Week in AI
V
Visual Studio Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
The Cloudflare Blog
博客园 - 【当耐特】
博客园 - 叶小钗
量子位
博客园 - 聂微东
S
SegmentFault 最新的问题
美团技术团队
Hugging Face - Blog
Hugging Face - Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
月光博客
月光博客
宝玉的分享
宝玉的分享
小众软件
小众软件
罗磊的独立博客
有赞技术团队
有赞技术团队
Stack Overflow Blog
Stack Overflow Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
JavaScript Closures Explained Like You're Learning Them f...
Anshul Sharma · 2026-05-30 · via DEV Community

JavaScript Closures Explained Like You're Learning Them for the First Time

Have You Ever Wondered How This Works?

Imagine you have a function:

function createCounter() {
  let count = 0;

  return function () {
    count++;
    console.log(count);
  };
}

const counter = createCounter();

counter();
counter();
counter();

Output:

1
2
3

At first glance this looks strange.

The variable count belongs to createCounter().

Once createCounter() finishes executing, shouldn't count disappear?

Then why does JavaScript still remember it?

The answer is: Closures.

But before understanding closures, let's understand how variables normally behave.


How Variables Normally Work

Consider this function:

function greet() {
  let name = "Anshul";

  console.log(name);
}

greet();

Output:

Anshul

After the function finishes:

greet();

the variable:

name

is removed from memory because it is no longer needed.

Think of it like this:

Function starts
    ↓
Variable created
    ↓
Function ends
    ↓
Variable removed

This is normal JavaScript behavior.


Now Let's Break the Rules

Look at this code:

function outer() {
  let name = "Anshul";

  return function inner() {
    console.log(name);
  };
}

const sayHello = outer();

sayHello();

Output:

Anshul

Something interesting happened.

The function outer() finished executing.

Yet inner() can still access:

name

How?


What JavaScript Actually Does

When JavaScript creates inner(), it notices that the function uses a variable from its parent scope:

name

Instead of deleting that variable, JavaScript keeps it alive.

It creates a hidden connection between:

inner()
      +
remembered variables

This connection is called a Closure.


The Simplest Definition

A closure is:

A function that remembers variables from its outer scope even after the outer function has finished executing.

That's it.

No complicated terminology required.


Visualizing a Closure

Step 1:

const sayHello = outer();

Memory:

outer()

name = "Anshul"

Step 2:

return inner;

JavaScript stores:

inner()
   |
   └── remembers name = "Anshul"

Step 3:

sayHello();

Output:

Anshul

Even though outer() no longer exists.


Real-World Example #1: Counter

Let's build a counter.

function createCounter() {
  let count = 0;

  return function () {
    count++;
    return count;
  };
}

const counter = createCounter();

console.log(counter());
console.log(counter());
console.log(counter());

Output:

1
2
3

Why?

Because the returned function remembers:

count

between executions.

Memory looks like:

counter()
      |
      └── count = 3

The value survives because of the closure.


Real-World Example #2: Private Variables

Suppose we're building a bank account.

We don't want anyone changing the balance directly.

Bad:

account.balance = 1000000;

Let's hide it.

function createAccount() {
  let balance = 1000;

  return {
    deposit(amount) {
      balance += amount;
    },

    getBalance() {
      return balance;
    }
  };
}

const account = createAccount();

account.deposit(500);

console.log(account.getBalance());

Output:

1500

Trying this:

console.log(account.balance);

Output:

undefined

The variable is protected inside the closure.


Real-World Example #3: Function Factory

Closures allow us to generate customized functions.

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

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

console.log(double(5));
console.log(triple(5));

Output:

10
15

Each function remembers its own value.

double()
   remembers multiplier = 2

triple()
   remembers multiplier = 3


Why Closures Are Important

Closures are used everywhere in JavaScript:

  • Event handlers
  • React Hooks
  • Debouncing
  • Throttling
  • Authentication systems
  • State management
  • Timers
  • Function factories

Even if you don't write closures intentionally, you're already using them.


Common Interview Question

What will this print?

function outer() {
  let x = 10;

  return function () {
    console.log(x);
  };
}

const fn = outer();

fn();

Answer:

10

Because the returned function remembers x.


Common Mistake

Consider:

for (var i = 1; i <= 3; i++) {
  setTimeout(() => {
    console.log(i);
  }, 1000);
}

Output:

4
4
4

Why?

Because all callbacks share the same variable.

Using let:

for (let i = 1; i <= 3; i++) {
  setTimeout(() => {
    console.log(i);
  }, 1000);
}

Output:

1
2
3

Each iteration gets its own closure.


Are Closures Bad for Memory?

Not at all.

But if a closure keeps referencing a huge object, JavaScript cannot remove that object from memory.

Example:

function createHandler() {
  const hugeData = new Array(1000000).fill("data");

  return function () {
    console.log(hugeData.length);
  };
}

Since the returned function uses hugeData, it stays in memory.

This can sometimes lead to memory issues if not handled carefully.


Final Thoughts

A closure is simply:

A function remembering variables from the place where it was created.

That's all.

Whenever a function accesses variables from an outer scope and keeps using them later, a closure is created.

Once you understand closures, concepts like:

  • Debouncing
  • Throttling
  • React Hooks
  • Memoization
  • State Management

become much easier to understand.

The next time someone says "closure," think:

Function + Remembered Variables = Closure