JavaScript Closure

Shivani Nalawade
2 min readApr 15, 2020

--

Closures are one of the key concepts of JavaScript and allow developers to write better code.

Javascript Clouser

Coding in JavaScript without an understanding of closures is like trying to speak English without an understanding of grammar rules

What is Clouser?

  • Closures are frequently used in JavaScript for object data privacy, in event handlers and callback functions, and in partial applications, currying, and other functional programming patterns.
  • Data privacy is an essential property that helps us program to an interface, not an implementation. This is an important concept that helps us build more robust software.
  • Closure are nested function which has access to the outer scope
  • After the outer function is returned, by keeping a reference to the inner function (the closures) we prevent the outer scope to be destroyed.

Why we use Clouser ?

  • Closures are important because they control what is and isn’t in scope in a particular function, along with which variables are shared between sibling functions in the same containing scope.
  • closures are commonly used to give objects data privacy.
  • The closure is a collection of all the variables in scope at the time of creation of the function.
  • closures are used when you don’t want to use global variables to avoid unnecessary multiple object’s access to single variable.

Things to remember:

  • A closure is an inner function which has access to the outer function scope
  • Every call of the outer function creates a new closure
  • Every call of the closure interacts with the same outer scope — which is accurate

Example : Clouser

function Adder(x) {
return function(y) {
return x + y;
};
}

var add5 = Adder(5);
var add10 = Adder(10);

console.log(add5(2)); // 7
console.log(add10(2)); // 12

  • In this example, we have defined a function Adder(x), that takes a single argument x, and returns a new function. The function it returns takes a single argument y, and returns the sum of x and y.
  • Adder is a function factory(function factory refers to the object). It creates functions that can add a specific value to their argument. In the above example, the function factory creates two new functions — one that adds five to its argument, and one that adds 10.
  • add5 and add10 are both closures. They share the same function body definition, but store different lexical environments. In add5’s lexical environment, x is 5, while in the lexical environment for add10, x is 10.

we can achieve two things using closures:

Abstraction:

In the abstraction we show only essential (necessary)data.

Encapsulation:

Encapsulation hide the complexity.

To better understand this concept please do watch the below video.It will resolve your all doubts:

--

--

No responses yet