DEV Community

 Bishnu Prasad Chowdhury
Bishnu Prasad Chowdhury

Posted on

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)