Javascript Closure

Closures are a powerful and often misunderstood concept in JavaScript. In simple terms, a closure is a function that remembers the variables and parameters in the scope where it was created, even after that scope has finished executing. This allows the function to access and manipulate those variables even when it's called in a different context.

let's explain closures in an even simpler way:

Imagine you have a lunchbox with some delicious food inside. You want to share this lunchbox with your friend, but you don't want them to see what's inside. So, you wrap the lunchbox in a special wrapper that only you can open. Now, you give the wrapped lunchbox to your friend.

In this analogy:

  • The lunchbox represents a function.

  • The delicious food inside the lunchbox represents some variables or data inside the function.

  • The wrapper represents a closure.

  • You and your friend represent different parts of the code or different functions.

Your friend can use the lunchbox (execute the function) and get the delicious food (access the variables) inside it, but they can't see what's inside directly because of the wrapper (closure). The closure allows the function to "remember" the variables even after it has finished executing, just like the wrapper keeps the lunchbox contents hidden even after you've given it to your friend.

Here's a simple code example to go along with the analogy:

function createLunchbox() {
  const deliciousFood = "Pizza"; // This is like the food inside the lunchbox

  function openLunchbox() {
    console.log("Inside the lunchbox:", deliciousFood);

  return openLunchbox; // This is like giving the wrapped lunchbox to your friend

const lunchbox = createLunchbox(); // You create the lunchbox (function)
lunchbox(); // Your friend opens the lunchbox (executes the function)

When you run this code, it will output:

Inside the lunchbox: Pizza

In this example:

  • createLunchbox is like creating the lunchbox with the delicious food (defining a function with some variables).

  • openLunchbox is like the lunchbox being opened by your friend (a function inside another function).

  • deliciousFood is like the food inside the lunchbox (a variable inside the function).

  • lunchbox() is like your friend opening the lunchbox and seeing the food (executing the inner function).

Closures are a powerful concept that allows functions to keep access to their private data, making them handy for many programming tasks, like handling events, creating private variables, and more.


I hope that it has cleared a basic understanding of Closure to you!!

Avatar for Anjali saini

Written by Anjali saini

Hi, my name is Anjali Saini and I'm a creative front-end web developer. I have a passion for creating beautiful, user-friendly websites and applications that are both functional and visually appealing


Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.