DEV Community

sagar
sagar

Posted on

1

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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay