Closures In JavaScript Explained Simply


This article demonstrates and briefly explains closures.
Let’s understand some definitions mentioned below.
Closure is a computer science term that defines how a function can maintain a record of the environment in which it was called. This means that a function can keep track of the arguments and variables it was initially called with, even when it’s called outside of that scope.
A closure is an inner function that has access to the outer (enclosing) function's variables—scope chain.
In other words, an inner function will always have access to the variables and parameters of its outer function, even after the outer function has returned.
Let’s see this with an example:
  1. //***********Example 1***************//  
  2. function yearsLeftForRetirement(retirementAge) {  
  3.     const message = ' years left for the retirement';  
  4.     return function calcluateYears(currentYear, birthYear) {  
  5.         const yearsLeftForRetirement = retirementAge - (currentYear - birthYear);  
  6.         console.log(yearsLeftForRetirement + message);  
  7.     };  
  8. }  
  9. const birthYear = 1985;  
  10. //Get years left for retirement in India  
  11. const retirementInIndia = yearsLeftForRetirement(62);  
  12. retirementInIndia(new Date().getFullYear(), birthYear);  
  13. //Get years left for retirement in US  
  14. const retirementInUS = yearsLeftForRetirement(65);  
  15. retirementInUS(new Date().getFullYear(), birthYear);  
  16. //Same can also be written as  
  17. yearsLeftForRetirement(65)(new Date().getFullYear(), birthYear);  
Clearly here we can see that the inner function has access to message constant and retirement age parameter which are outside the scope of the inner function (CalculateYears).
Also, the inner function has access to them even after the yearsLeftForRetirement function is called because that is why we are able to log the message in the console.
Closures In JavaScript Explained Simply
A closure gives you access to an outer function’s scope from an inner function.
  • To use a closure, simply define a function inside another function and expose it. To expose a function, return it or pass it to another function
  • The inner function will have access to the variables in the outer function scope, even after the outer function has returned.
Some use cases for closures are event handlers, timeouts, intervals, callbacks, and keeping variables private within functions.
Let’s see another example,
  1.  //***********Example 2***************//  
  2. const getValue = value => {  
  3.    return {  
  4.       get: () => value  
  5.       };  
  6.    };  
  7. console.log(getValue('This is a test'));  
In the example above, the get() method is defined inside the scope of getValue(), due to which get method gets access to any variable which has been passed into getValue().
So clearly here getValue() is returning an object which has a method called get(), which is here simply returning the value passed to the getValue().
So, if we simply write the below statement.
  1. console.log(getValue('This is a test'));  
The output will look something like.
Closures In JavaScript Explained Simply
So, in order to get the value, we need to call it this way.
  1. console.log(getValue('This is a test').get());   
The output will look something like.
Closures In JavaScript Explained Simply
Drawbacks of using Closures
The most important thing to consider while using Closures is to look for memory management.
The drawback of using closures without thought is that it could lead to memory leaks.
For example- if there are 20 functions that are referencing a common variable, then this variable will exist until all those 20 functions will get garbage collected.
Cheers to coding!!