TIL Closure as a backpack
POSTED ON:
TAGS: javascript advanced
Closure as a backpack.
The Backpack concept is a mental model to think about how closure saves data behind the scenes.
The example in the StackOverflow is so freakin good, it's one of the best I ever read.
CHALLENGE:
Incrementing a counter.
SOLUTIONS:
Attempt 1 - The global variable #
You could use a global variable, and a function to increase the counter:
var counter = 0;
function updateClickCount() {
++counter;
// Do something with counter
}
Issue: Any script on the page can change the counter, without calling updateClickCount().
Attempt 2 - Declaring the variable inside the function #
function updateClickCount() {
var counter = 0;
++counter;
// Do something with counter
}
Issue: Every time updateClickCount() function is called, the counter is reset to 0.
Attempt 3 - Wrap the function with a inner function #
function countWrapper() {
var counter = 0;
function updateClickCount() {
++counter;
// Do something with counter
}
updateClickCount();
return counter;
}
Now, you can call updateClickCount()
to add the counter!
Issue: How exactly do you call updateClickCount()
from inside the function? You could try to expose the updateClickCount()
function with strategies from here.
But then, you're adding a lot more complexity to this.
Let's look at this:
Attempt 4 - Closure and the backpack #
const updateClickCount = (function(){
let counter = 0;
return function(){
++counter;
return counter;
}
})();
console.log(updateClickCount()); // 1
console.log(updateClickCount()); // 2
console.log(updateClickCount()); // 3
First, this is a IIFE statement.
Next, the anonymous function is actually a backpack. It saves the data in it's backpack and hides it away from scope. Nobody can modify counter++ but itself.
REFERENCE:
The amazing Will Sentance covers Closure in details in his Frontend Masters course.
https://frontendmasters.com/courses/javascript-hard-parts-v2/closure-introduction/
https://stackoverflow.com/a/39045098/4096078
SERIES:
- Closure The Basics
- Closure Example with class-like methods
- Closure Example with private data
- Closure Example as a backpack
Related TILs
Tagged: javascript