This content originally appeared on DEV Community and was authored by Barnabas Babatunde
Introduction:
In this article, I am going to walk you through the basics of closure in JavaScript, as simply as I can.
Prerequisite:
If you have a prior knowledge of lexical scope in JavaScript and for some reason, you have not yet grasped the concept of closure, then this article is for you.
Why You Should Understand Closure:
- Closure is all around us.
- Closure forms the foundation for separating large codes into separate, yet interdependent modules.
- Chances are that you're already using closure in your code without even knowing it.
At the end of this article, you should:
- have a good grasp of the basics.
- be able to recognize closures in your code. As I pointed out earlier, you're probably using it already, without knowing.
Let's dive in.
What Is Closure?
Closure is when a function can still remember and access its lexical scope even when that function is executed outside its lexical scope. Lexical scope means: the scope where the function was defined.
Illustration:
function hour(){
var hr = 2;
function min(){
console.log(hr);
}
return min;
}
var time = hour();
time(); //output: 2
Let's walk through the above code snippet.
- First, we define a function
hour. This function creates a scope which wraps (or hides) everything in it from the outside world. - Next, within
hour, we declare a variablehrand assign it a value of 2. - Still within
hour, we define another functionminwhich creates its own scope within the scope ofhour. Notice thatminreferences the variablehrin its definition. - Finally within
hour, we return outmin. - Moving outside the scope of
hour,houris executed (or called). The result of this call (min) is assigned to a new variabletime. - We then execute
time, which of course executes our returned functionmin. Sominis executed outside the scope we declared it in.
We get an output of 2 which is the value of hr. This is shocking!
We expect function hour(and everything in it, including hr) to be garbage-collected immediately we exit the function(at the return statement). So how come min can still access the variable hr and the entire scope of the hour function? This is closure at work.
Closure lets min to continue to have access to the scope it was defined in, which is hour in our case. We can say that closure kept the scope of hour alive for min to access at anytime (and at any location) within the program.
The Famous setTimeout Function:
Using the famous setTimeout function is one of many ways we use closure in our everyday code.
function delay(){
var response = "Ok";
setTimeout(function timeCount(){
console.log(response);
}, 2000);
}
delay();
- First we author a lexical scope by defining a function
delay. - Next, within
delay, we declare a variableresponseand assign the string"Ok"to it. - Next, we create a function called
timeCountand pass it tosetTimeoutas a first argument, alongside2000as the second argument. - Finally we execute
delay. - Be aware that
timeCounthas a closure over the scope ofdelay. Hence whentimeCountis executed withinsetTimeout2000 milliseconds later, it still has access to the scope ofdelay, even whendelay's scope should have died off already. This is closure at work again.
Conclusion:
In the last few minutes (or seconds, Lol), We have learned the basic concept of closure, and seen how it is used in code, and in the setTimeout function.
In the next article, we will take a deeper dive into closure - how it works hand in hand with loops, and how it forms the foundation for module patterns. We will also look at the concept of PLSRD (Persistent Lexically Scoped Referenced Data).
Till next time folks ✌
This content originally appeared on DEV Community and was authored by Barnabas Babatunde
Barnabas Babatunde | Sciencx (2021-05-22T12:09:04+00:00) An Intro To Closure In JavaScript. Retrieved from https://www.scien.cx/2021/05/22/an-intro-to-closure-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.