DEV Community

Priyaramu
Priyaramu

Posted on

Closure in Javascript

What is a Closure?

In JavaScript, when you create a function inside another function, the inner function can use the variables of the outer function. Normally, once a function finishes running, its variables are gone. But in closures, the inner function keeps those variables in memory.

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

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

  return inner;
}

const myFunction = outer();
myFunction();
Enter fullscreen mode Exit fullscreen mode

Difference Between Function and Closure
Function
A normal function executes its code and then finishes. Once it is done, the variables inside the function are removed from memory and cannot be used again.In a normal function, variables are often global and can be changed by anyone, which makes them unsafe.

let count = 0;

function add() {
  count++;
  console.log(count);
}
Enter fullscreen mode Exit fullscreen mode

Closure
A closure is a function that remembers the variables from its outer function even after the outer function has finished running. These variables stay in memory and can be used later whenever the function is called.In a closure, variables are private and protected, so they cannot be accessed or modified from outside.

Closures are useful when we need to store data, maintain state, or protect variables from outside access.

function counter() {
  let count = 0;

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

const add = counter();
Enter fullscreen mode Exit fullscreen mode

Closures are used in different ways like:

  • storing values
  • protecting data
  • creating functions
  • handling events

Memory Diagram:
Call outer() for Variable count is created

Memory:
outer()
 └── count = 0
Enter fullscreen mode Exit fullscreen mode

Return inner()

Memory:
outer()
 └── count = 0

fn → inner() function
      ↑
      remembers count
Enter fullscreen mode Exit fullscreen mode
  • inner() is returned and stored in fn
  • It keeps a reference to count

Outer Function Ends

Memory:
count = 0   ✅ (NOT deleted)

fn → inner()
Enter fullscreen mode Exit fullscreen mode
  • Normally count should be deleted
  • But it stays because inner() uses it

Call fn()

count = 0 → 1

Output: 1
Enter fullscreen mode Exit fullscreen mode

Call fn() Again

count = 1 → 2

Output: 2
Enter fullscreen mode Exit fullscreen mode
inner()  
  └── carries → count
Enter fullscreen mode Exit fullscreen mode

Even if outer() is gone, inner() still has the data

The inner function keeps a reference to the variable count, so it stays in memory and continues to update each time the function is called.

Top comments (0)