Introduction
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:
- //***********Example 1***************//
- function yearsLeftForRetirement(retirementAge) {
- const message = ' years left for the retirement';
- return function calcluateYears(currentYear, birthYear) {
- const yearsLeftForRetirement = retirementAge - (currentYear - birthYear);
- console.log(yearsLeftForRetirement + message);
- };
- }
- const birthYear = 1985;
- //Get years left for retirement in India
- const retirementInIndia = yearsLeftForRetirement(62);
- retirementInIndia(new Date().getFullYear(), birthYear);
- //Get years left for retirement in US
- const retirementInUS = yearsLeftForRetirement(65);
- retirementInUS(new Date().getFullYear(), birthYear);
- //Same can also be written as
- 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.




Join the conversation! Your thoughts help the community grow.