So Closures, one of the most confusing topic for developers😵. Let us understand what closures are in simple terms
"A closure gives a function access to all the variables of its parent function even after the parent function has returned"
OR
"A closure makes sure that a function does not loose connection to variables that existed at the functions birthplace"
See, as simple as that 😮
Now, let us understand closure using some code
function A(){
let passengers = 0;
return function(){
passengers++;
console.log(`${passengers} passengers`)
}
}
const c = A(); //c is the function returned by the parent function
c(); //1 passengers;
c(); //2passengers;
c(); //3passengers;
In the above code snippet, we can see that A function returns an function where we are trying to access passengers variable which is declared in the parent function(A function).
But how are we able to access the variable since function A has already returned 🤔
This is where Closures come into picture. The child function will always have access to the variable "passengers".
Lets see how this code works
The initial value of passengers is 0.
- When we call c for the first time the variable is incremented to 1 and "1 passengers" is logged to the console.
The reference of passengers is then updated to value 1.
- As the reference of passengers has value 1, When we call c for the next time the variable will be incremented form 1 to 2 and "2 passengers" is logged.
The reference of passengers is then updated to value 2.
- In the 3rd function call, the value of the variable is then incremented to 3 and "3 passengers" is logged
One huge take away from the above example is that:
The child function does not store the value of the variable, it stores an actual reference to the variable so it always has access to the latest value of the variable.
Advantages of Closures:
- Using closures we can achieve Data privacy/Data hiding.
- We can implement function currying with the help of closures.
Disadvantages of Closures:
- Closures may lead to over consumption of memory.
- Variables in a closure are not garbage collected.
- Memory leaks in browsers if closures are not handled properly.
That's it. Hope you got a basic understanding of how closures work in JavaScript