Closures are created when a function is defined inside another function, and the inner function refers to the variables declared in the outer function's scope chain. In other words, a closure is created when an inner function has access to the variables of an outer function.
In this blog, we'll explore what closures are, how they work, and provide code examples to help you better understand them.
To understand closures conceptually, we need to understand two main concepts: variable scope and the execution stack.
When a variable is declared inside a function, it is said to be in the function's scope, which means other functions outside of that scope cannot access the variable.
Here is an example:
The code logs "Chloe" because the inner function innerScope has access to the variable name declared in the outer function scopeExample.
Each time a function is called, it is added to the top of the stack. When the function completes execution, it is removed from the stack.
Here's an example to illustrate how functions are added and removed from the execution stack:
The output is:
- Inside first function
- Inside second function
This happens because firstFunction is called first, and then it calls secondFunction. When secondFunction completes execution, it is removed from the stack, and then firstFunction completes execution and is removed from the stack.
Now that we have covered variable scope and the execution stack, let's dive into closures.
Closures are created when an inner function has access to the variables of an outer function even after the outer function has completed execution and been removed from the stack.
Consider the following code:
The outerFunction function returns a reference to the innerFunction. We store this reference in a variable myName.
myName now has access to the name variable declared in outerFunction even though outerFunction has completed execution and has been removed from the stack.
In this example, login and logout functions have access to the variables username and password, but these variables cannot be accessed from outside the user function.
This means that username and password are private variables. login and logout can use them but cannot be accessed from outside the user function.
Closures are frequently used in event listeners.
In this example, the init function has access to the button variable. The addEventListener function creates a closure that has access to the button variable, even after the init function has completed execution and been removed from the stack.
When the button is clicked, the closure executes and displays an alert message, demonstrating the concept of closures in event listeners.
I hope this blog helped you understand closures better. Thank you for reading!