Look ma, there's a closure!
I find closures to be one of the most confusing JavaScript concepts, right up there with Promises. As a beginner, I found it hard to wrap my head around the concept of closures even though I used them every time. But I am getting the hang of them, so I am writing about it.
When does a closure happen?
There is a closure when a function is able to access variables outside of it. Let’s use this definition to walk through an example below:
let variableOne = "Hello";
function randomFunctionHere() {
/* some code here below*/
let variableTwo = "World!";
console.log(variableOne + variableTwo);
}
randomFunctionHere();
What we have here is this function randomFunctionHere accessing the variable variableOne outside of it. So, when we call the function randomFunctionHere, it prints out:
-> HelloWorld!
Although, the variable variableOne is not defined within the scope of our function randomFunctionHere, our function randomFunctionHere is still able to access and use that variable to carry out some operation, in this case, a string concatenation. Now, that's a closure.
In the example above, the variable variableOne is defined in the global scope and is therefore, a global variable. Global variables are variables that are defined in the global scope (outside of any code block) and they belong to the window object which means that they can be accessed anywhere in our code.
We also have a closure when a function defined within the scope of another function is able to access variables outside of it. Let’s look at the example below:
function myFunction() {
var randomNumber = 10;
function myInnerFunction() {
console.log(randomNumber + 20);
}
myInnerFunction();
};
randomFunctionHere();
->30
In JavaScript, functions are able to access variables defined within its parent’s scope as we can see in the example above. Variables defined within a function’s scope (inside the function itself) are called local variables because they are local to the function. So the output produced when the function myFunction is called can be traced to the code on line 4 which uses the variable defined in the scope of its parent function.
I hope this really really simple intro to closures helps!
(In a way, as I mentioned earlier, this is me trying to write about concepts as I grasp them. I hope this helps whoever is reading this).