Scopes And Closures Re-Explained: Part 2
Welcome back to Confusion: Part 2. I mean Scopes & Closures: Part 2. If you missed the first part where I talked about scopes, you can find it here.
In this part, I will be going over closures! Closures can be a scary and intimidating topic. Just look blow at how MDN defines it:
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment).
In this article I will breakdown the concept with some examples. Closure is such an important concept that we as developers use it everyday in our code whether we know it or not!
Closure Definition Simplified
Closure refers to a feature in which an inner function has access to variables in an outer function scope, even after it has already been executed. Whenever a function is created in JavaScript, a closure is created as well.
An closure has three scopes:
- Local Scope — Access to its own variables.
- Parent Function Scope — Access to variables with the outer function.
- Global Scope — Access to global variables.
Let’s Take a Closer Look
Here is a simple example.
Here we have an parent function that contains the variable name
which has been defined. It also creates an inner function.
The inner function has a local variable greeting
. The inner function can access the variable in the parent function which is why it is able to output it in the console.
Breakdown
In line 12, the outer function is invoked for the first time. Lets see what is happening here starting at the top:
- The
name
variable is created and its value is “Selene”. - The inner function is declared and returned in line 5.
- The content of the inner function is stored in the variable
greet
. - After it is stored, the outer function finishes execution and its scope no longer exists. (Local variables only exist for the duration of its function). Once a function returns, any local variables are deleted.
- However, when greet is invoked, the name variable is still accessible and still used. This is why our output is “Hello Selene”.
How? Closures! The inner function is created when the outer function is invoked. At this point a closure is formed.
Lets go back to MDN’s definition.
A closure is the combination of a function and its lexical environment, or references to its surrounding state.
When the inner function is created, it holds a reference to its parents lexical environment in which the name
variable exists. It “remembers” the environment in which it was created which will included any local variables that are considered in scope.
And that is the power of closures!
Conclusion
Closure is a concept that a key feature in JavaScript and in other programming languages. We use it in our daily programming life but it can be hard to grasp fully. But by knowing its actual power, we can gain better control of our code.