DEV Community

sagar
sagar

Posted on

Clousers in Javascript?

Image description

What is a closure?

A closure is a feature in JavaScript where an inner function has access to the outer (enclosing) function’s variables

_

“A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function.”
_

function outer() {
  var count = 0;

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

  return inner;
}

var counter = outer();

counter(); // 1
counter(); // 2
counter(); // 3
Enter fullscreen mode Exit fullscreen mode

In the above code

The inner function will have access to the variables in the outer function scope, even after the outer function has returned.

even after outer function done executing the inner function can have access to outer function variable means when we return inner function the inner function return with its surrounding variable and this is called closures.

Top comments (0)