Member-only story

Understanding Closures in JavaScript: From Confusion to Clarity

Rajesh Dhiman
3 min readNov 21, 2024

--

Imagine This…

You’re working on a project, and you need a function to “remember” the values of variables — even after the function has finished running. Closures are like a magical backpack that lets you carry knowledge from a previous lesson wherever you go in your code. It’s one of the most powerful yet misunderstood concepts in JavaScript. But don’t worry — by the end of this guide, closures will go from head-scratching to “aha!”

What’s a Closure? Simplified Definition and Analogy

A closure is when a function “remembers” its surrounding state (the variables in its scope) even after the outer function has finished executing. Let’s break this down with a relatable analogy:

Real-Life Analogy: The Backpack of Knowledge

Imagine you’re a student. You have a backpack with your notes, pens, and books. You leave the classroom (your outer function), but you still have access to everything in your backpack (your closure). Whenever you need to solve a problem later, you can pull out the knowledge you saved in your backpack.

Simplified Definition

In JavaScript, closures happen when:

  1. A function is defined inside another function.
  2. The inner function “remembers” the variables of the outer function.

--

--

Rajesh Dhiman
Rajesh Dhiman

Written by Rajesh Dhiman

Rajesh Dhiman is a full-stack developer, technical architect, and mentor with 12+ years of experience. https://www.rajeshdhiman.in/

Responses (2)