JavaScript Closures Simply Explained
JavaScript
10/07/2021
They key to understanding closures is scope, because closure is nothing more than the outer scope of a function.
Let's look at an example:
JAVASCRIPT
/* Outer scope */let someVariable = 'someValue'
function printVariable() { /* Inner scope */ console.log(someVariable)}
printVariable() // someValue
The function printVariable
has access to any variables defined outside of it, e.g. someVariable
. The successful log of this variable proves so.
Nested functions
Closures are often discussed in the context of nested functions, using the following typical example:
JAVASCRIPT
function outerFunction(outerVariable) { return function innerFunction(innerVariable) { console.log(outerVariable, innerVariable) }}
const anotherFunction = outerFunction('outside')anotherFunction('inside') // outside, inside
As you can see, innerFunction
still has access to any variables from its parent function, even after the parent has been called.
However, whenever you work with closures, you should be acutely aware ⚠️ of the concept of stale closures!