Javascript closures Javascript closures

by Shreyansh Jha

Closure is one of the most important concepts in JavaScript. It is widely discussed and still one of the most confused concepts. Let’s understand it in a simpler way.

What are Closures?

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. In JavaScript, closures are created every time a function is created, at function creation time.

Let’s take it as an example:-

function func1() {
let count = 0;
return function () {
count++;
console.log(count);
};
}

const func2 = func1();

func2(); //count becomes 1
func2(); //count becomes 2
func2(); //count becomes 3

Here, in this example :

  • func1() initializes a variable count set to 0 and then return another function that increments count by 1.

  • Then func2() is initialized through func1() and hence it’s also a function here.

  • Count=0, every time func2() is called count is not initialized to everytime. Rather count remembers its previous incremented value and uses that to increment furthur.

In simpler words,

Closures are useful because they let you associate data (the lexical environment) with a function that operates on that data. This has obvious parallels to object-oriented programming, where objects allow you to associate data (the object’s properties) with one or more methods.

Consequently, you can use a closure anywhere that you might normally use an object with only a single method.

Note: A lexical scope in JavaScript means that a variable defined outside a function can be accessible inside another function defined after the variable declaration.