Closures
A closure refers to the lexical context a function was declared in and the variables it has access to. Closures allow us to dynamically create functions, implement encapsulation, and create interfaces to interact with our code. Learn how to use them to perform each of these tasks.
We'll cover the following...
Dynamically Generating Functions
Let’s say we want to write a function that lets us add 10
to any number.
function add10(num) {
return num + 10;
}
We want another function that lets us add 20 to any, and another that lets us add 30, and another that lets us add 40, and 50. Let’s write them.
function add20() {
return num + 20;
}
function add30() {
return num + 30;
}
...
Writing all of these function becomes tiresome and requires a lot of code duplication, something we always want to avoid. We want an easier way to write these functions.
Scope Persistence
When a function is created, it retains access to the scope that it was created in. If it’s created inside another function, it retains access to the scope of that outer function even after that outer function returns.
function fnGenerator(str) {const stringToLog = 'The string I was given is "' + str + '"';return function() {console.log(stringToLog);}}const fnReturned = fnGenerator('Bat-Man');fnReturned(); // -> The string I was given is "Bat-Man"
We’ve just created a closure. MDN defines a closure as
The combination of a function and the ...