Published on

How closure works in javascript?

How closure works in javascript?

How closure works in javascript?

Javascript: Closure

A closure is a combination of:

  1. A function and
  2. A reference to that function's outer scope (lexical environment)

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.

What is Lexical Environment in Closure?

Lexical Environment: It is part of every execution context (stack frame) and is a map between identifiers (i.e. local variable names) and values.

In the following code, inner forms a closure with the lexical environment of the execution context created when outer is invoked, closing over variable secret:

function outer() {
  const secret = Math.trunc(Math.random() * 100);
  return function inner() {
    console.log(`The secret number is ${secret}.`);
  };
}
const f = outer(); // `secret` is not directly accessible from outside `outer`. `outer` return a function which will be invocked letter.
f(); // The only way to retrieve `secret`, is to invoke `f`

What is the use of Closure function?

When a private state is required for a function, closures come in handy.

  1. Private Instance Variables

In the following code, the function displayName closes over the details of the person.

function Person(first_name, last_name) {
  return {
    displayName() {
      return `${first_name} ${last_name} )`;
    },
  };
}

const person = new Person("Sachin", "Tendulkar");
console.log(person.displayName());

Read more here about Private Members in JavaScript

  1. Functional Programming(Curring function)
function curry(fn) {
  const args = [];
  return function inner(arg) {
    if (args.length === fn.length) return fn(...args);
    args.push(arg);
    return inner;
  };
}

function sum(a, b) {
  return a + b;
}

const curriedSum = curry(sum);
console.log(curriedSum(2)(3)()); // 5

Conclusion

  • Whenever a function is declared in JavaScript closure is created.
  • Returning a function from inside another function is the classic example of closure, because the state inside the outer function is implicitly available to the returned inner function, even after the outer function has completed execution.
  • A closure is created when a function is declared; this closure is used to configure the execution context when the function is invoked.
  • A new set of local variables is created every time a function is called.
  • What will be the Output of below snippet?
  1. Without Closure
for (var i = 0; i < 10; i++) {
  setTimeout(function () {
    console.log(i);
  });
}
// Expected Output: 0 1 2 ... 8 9
// but due to `var` variable
// Output: 10 times 10
  1. Solution With Closure
for (var i = 0; i < 10; i++) {
  (function (i) {
    setTimeout(function () {
      console.log(i);
    });
  })(i);
}

// Output: 0 1 2 ... 8 9