Today I Learned - Rocky Kev

TIL some more examples of closure

POSTED ON:

TAGS:

I like what Will Sentance calls closure -- he refers it to 'a backpack'.

The technical definition:

A closure is a combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment).

In other words:

You have a wrapper function, with variables that piggyback (backpack) and a return function.

When you use that wrapper function, your backpack data stays there.

Code examples

function outer(arg) {
let a = 5;
function inner(){
console.log(a + arg);
}
inner();
}
outer(); //5

Benefits

I yoinked this list from How Closures Work in JavaScript: A Guide btw.

1 - Private variables and methods

Because it's enclosing variables and methods, you can't accidentally reach in and modify it. The only entry point is the outer function.

function counter(){
let count = 0;

return function incrementCounter(){
count++;
}
}

var counter1 = counter();
counter1(); //1
counter1(); //2

var counter2 = counter();
counter2(); //1
counter2(); //2
counter2(); //3

2 - Data hiding and encapsulation

It's private, and hidden! You can't even call it directly.

This is one of those 'Google Interview' questions!

function counter() {
var _counter = 0;
// return an object with several functions that allow you
// to modify the private _counter variable
return {
add: function(increment) { _counter += increment; },
retrieve: function() { return 'The counter is currently at: ' + _counter; }
}
}

// error if we try to access the private variable like below
// _counter;

// usage of our counter function
var c = counter();
c.add(5);
c.add(9);

// now we can access the private variable in the following way
c.retrieve(); // => The counter is currently at: 14

via https://www.coderbyte.com/algorithm/3-common-javascript-closure-questions

3 - Currying

That's when we do things like this:

function sum => (a) => (b) => (c) => a + b + c

console.log(sum(1)(2)(3));

That's Functional Programming BAY-BEE!

4 - Function Factories

It'll allow you to scaffold functions.

To explain:

function Job(title) {
    return function(prefix) {
        return prefix + ', ' + title;
    };
}
const sales = Job('Salesman'); // returns "${prefix}, Salesman"
const manager = Job('Manager'); // returns "${prefix}, Manager"

sales('David Hayter'); // returns "David Hayter, Salesman";
manager('David Hayter'); // returns "David Hayter, Manager";

5 - Performance

If that backpack is storing an array with a billion elements, it'll save that array in memory ONCE!

To give a real-world example:

// standard way
const day = function(daynum) {

const weekdaysArray = ["mon", "tue", "wed", "thurs", "fri" ];

return weekdaysArray[daynum];

}

day(0);


// with closure
const day = (function() {

const weekdaysArray = ["mon", "tue", "wed", "thurs", "fri" ];
return function(daynum) {
return weekdaysArray[daynum]
};
})();

day(1);

The "standard way", that weekdaysArray is being created/destroyed EVERY SINGLE TIME the function is called.

But with closure, it never gets garbage collected!


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.