In this article, we will learn about closures

start

According to MDN docs,

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.

In simple words, it means :

A function bind together with its lexical environment(function +lexical scope). It also holds a reference to the parent's lexical scope.

If you want to know more about lexical scope you can refer here: Lexical scope

Example:

function x(){
var a=13;
function y(){
console.log(a)
}
y();
}
x();
//output:13

Example 2:

function x(){
var a=13;
function y(){
console.log(a)
}
return y;
}

var z=x();
console.log(z)

//output:
ƒ: y(){
console.log(a)
}

In some programming languages, if a function returns then it becomes ready for garbage collection or is completely removed from the heap and local variables within a function exist for just the duration of that function's execution, but in Javascript, if there is closure then the parent function variables remain in the heap.

Closures and settimeout

Example 1:

for(var i = 0; i < 4; i++) {
   setTimeout(function() {
      console.log(i);
   }, i * 1000);
}

In the code above,

we expect output to come as : 0 1 2 3

but the output comes as 4 4 4 4 This is due to closure, as we know due to closure it remembers its reference to i . The js engine makes a copy of variable i and attaches a timer to it. So all the copies of i refer to the same variable i .

Example 2:

for(let i = 0; i < 4; i++) {
   setTimeout(function() {
      console.log(i);
   }, i * 1000);
}
//output:
0
1
2
3

Now here let is block-scoped so each and every time loop runs the variable i is a completely new copy of i.

Uses of Closure

  • Module pattern

  • Currying

  • memorize

  • Settimeout()

  • iterators

Advantages

  • module patterns

  • Currying

  • Higher-order functions

  • Data hiding and encapsulation

Disadvantages

  • Variables used by closure are not garbage collected
  • Lead to memory leaks if variables are not handled properly

Garbage collector

It is a program in the js engine which monitors allocated memory and
frees up the memory when no longer needed.

References

That's all for this article thanks a lot.

Thanks