DEV Community

 Bishnu Prasad Chowdhury
Bishnu Prasad Chowdhury

Posted on

1 1

Closures in JavaScript

In JavaScript we can pack a function inside another function. When one function A is inside another function B then function A is called outer function while function A is called inner function and this phenomenon is called a closure.
In closure the inner function can have access to the outer function scope.

function B() {
  let x = 7;
  function A() {
     console.log(x);
  }
  return A;
}

var c = B();
c();

>7
Enter fullscreen mode Exit fullscreen mode

Closures are used to make private function or variables that has limited access. The outer function of a closure cannot access the inner function scope so it can be used to hide data.

Apart from this use closure do have drawbacks where as long as closure is running memory cannot be garbage collected resulting to memory leaks. This can be avoided by making them null force fully after the use.

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay