Logo

dev-resources.site

for different kinds of informations.

Clousers in Javascript?

Published at
6/21/2024
Categories
javascript
webdev
programming
Author
sagar
Categories
3 categories in total
javascript
open
webdev
open
programming
open
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

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.

Featured ones: