A closure is a function having access to the parent scope, even after the parent function has closed.
Let’s break it down. Even better with an example.
Let us consider an example of salary. There is basic salary which we all know about. Bonus is something which is given over the basic salary.
In the following code we will try to get the final amount after we add bonus.
basic(basicAmount) { return function amountWithBonus(bonusAmount) { return basicAmount + bonusAmount } }
Next, lets us call the above function with a basic salary amount and store it in a variable called calculateBasicWithBonus.
let calculateBasicWithBonus = basic(300)
Now what happens after the above statement is that, the basic function is called with the argument 300. As we have written above, the basic function will return another function called amountWithBonus.
So now, the calculateBasicWithBonus variable contains the function amountWithBonus.
Well, so there is nothing new so far. But, take a look at what the amountWithBonus function contains. It has the value basicAmount which we passed to the function basic as its accessible variable, or also know as closure.

In the above image you can see the closure has basicAmount: 300 in its scope.
few points to note here,
1. The function basic is already been called.
2. the variable basic amount is not a parameter of amountWithBonus function.
3. But because lexical scope, the basicAmount is available for amountWithBonus to use it.
Now let’s call the calculateBasicWithBonus with a bonus amount we want.
Let’s say 40 is the amount we want to add. This function will return the total amount by adding the basic and the bonus. The code will look like the following.
const totalSalaryWithBonusAdded = calculateBasicWithBonus(40); console.log('totalSalaryWithBonusAdded: ', totalSalaryWithBonusAdded); // console output is totalSalaryWithBonusAdded: 340
As we see here even though we called the calculateBasicWithBonus with 40 it had retained the basicAmount (300) value which we had passed for the basic function and returned the final amount by adding it to the bonus.
This scenario, where a function is able to access a variable which is of it’s parent’s scope is called a closure.
Leave a Reply