Understanding Closure in JavaScript

Understanding Closure - Functional Programming in JavaScript

Jobayer Hossain
Name
Jobayer Hossain
Twitter
@Jobayer977

In this article, we will learn about closure in JavaScript. We will learn what closure is, how it works, and how we can use it in our code. We will also learn about the scope in JavaScript, and how it is related to closure.

Understanding Scope in JavaScript

Let's see an real world example which will help us to understand the concept of scope. Think about money like this: The US dollar is like a global scope that works everywhere in the world. Anyone, from any country, can use it to buy things. But, when we talk about a specific country, like Bangladesh, its money is like a local scope – it only works within that country. So, if you have Bangladeshi money, you can use it there, but not everywhere else.

In JavaScript, scope is like the country. There are two types of scope in JavaScript: global scope and local scope. Global scope is like the US dollar – it works everywhere in the code. Local scope is like Bangladeshi money – it only works in a specific part of the code. like inside a function or a block.

An example of scope:

var amountInUSD = 100;
function buySomething() {
  var amountInBDT = 10000;
  console.log("Access USD from inside: " + amountInUSD);
  console.log("Access BDT from inside: " + amountInBDT);
}
 
buySomething();
 
console.log("Access USD from outside: " + amountInUSD);
console.log("Access BDT from outside: " + amountInBDT);
 

Here we created a variable named amountInUSD in the global scope. and also we created a function named buySomething and inside the function we created a variable named amountInBDT in the local scope. Now if we try to access the amountInUSD variable from inside the function we can access it. Because the amountInUSD variable is in the global scope. as well as if we try to access the amountInBDT variable from inside the function we can access it. Because the amountInBDT variable is in the local scope. But if we try to access the amountInBDT variable from outside the function we will get an error. Because the amountInBDT variable is in the local scope. And it only works inside the function. So we can't access it from outside the function. like our Bangladeshi money only works inside Bangladesh. And if we try to access the amountInUSD variable from outside the function we can access it. Because the amountInUSD variable is in the global scope. And it works everywhere in the code. like the US dollar works everywhere in the world.

Now let's get back to our main topic, Closure.

Closure

In JavaScript we can create functions inside other functions. When we do this, the inner function has access to the variables in the outer function.

function outerFunction() {
    var outerVariable = 100;
    function innerFunction() {
        console.log(outerVariable);
    }
    return innerFunction;
}

In this example, we created a function named outerFunction and inside the function we created a variable named outerVariable and also we created another function named innerFunction inside the outerFunction. Now if we try to access the outerVariable variable from inside the innerFunction we can access it. Because the innerFunction has access to the variables in the outerFunction. And this is how a closure are created.

Now if we print the outerFunction in the console using console.dir(outerFunction()) we will see something like this.



outerFunction

In console scopes we have two scopes one is global and another is closure and in closure scope we have outerVariable variable. Because the innerFunction access the outerVariable variable from inside the outerFunction. But one thing is keep in mind if the innerFunction doesn't access the outerVariable variable from inside the outerFunction then the outerVariable variable will not be in the closure scope. and also if the outerVariable is defined in the global scope then it will not be in the closure scope.

Now let's see an real world use case of closure.

Use Case of Closure

Let's say we want to create a function that calculates the tax for a given income.

function calculateTax(taxRate) {
  return function (income) {
    return income * taxRate;
  };
}
 
const calculate10PercentTax = calculateTax(0.1);
 
const taxForJon = calculate10PercentTax(50000);
const taxForMike = calculate10PercentTax(75000);
 
console.log(taxForJon); // Output: 5000
console.log(taxForMike); // Output: 7500
 

We first created a function named calculateTax which takes a taxRate as an argument and returns another function. And inside the returned function we calculate the tax for a given income. And then we created a function named calculate10PercentTax which takes a taxRate as an argument and returns another function. And inside the returned function we calculate the tax for a given income. And then we created two variables named taxForJon and taxForMike and we called the calculate10PercentTax function with two different income. And we stored the returned value in the taxForJon and taxForMike variables. So here closure helps us to create a function that calculates the tax for a given income. And we can use this function to calculate the tax for different income without writing the same code again and again.

Conclusion

So in simple words closure is a function that has access to the variables of another function. And we can use closure to create private variables and functions. that's all for this article. I hope you have learned something new today.