Today I Learned - Rocky Kev

TIL Closure as a backpack

POSTED ON:

TAGS:

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:


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.