Today I Learned - Rocky Kev

TIL Why use Closures

POSTED ON:

TAGS:

For a reminder of what Closure is:

var e = 10;
function sum(a){
return function(b){
return function(c){
// outer functions scope
return function(d){
// local scope
return a + b + c + d + e;
}
}
}
}

console.log(sum(1)(2)(3)(4)); // log 20

Now you might be asking, why even use it? Why not just flatten it out so it's just one function with one return statement?

Advantages of Closures

1 - Protecting Variables and Methods

I can now define the original rent, and then protect that value while calling inner functions (methods) to modify it.

var rentPrice = function(initialRent) {
var rent = initialRent;
// Define private variables for the closure
return {
getRent: function() {
console.log(rent);
},
incRent: function(amount) {
rent += amount;
console.log(rent);
},
decRent: function(amount) {
rent -= amount;
console.log(rent);
}
}
}

var Rent = rentPrice(8000);

// Access the private methods
Rent.incRent(2000);
Rent.decRent(1500);
Rent.decRent(1000);
Rent.incRent(2000);
Rent.getRent();

2 - Data Hiding and Encapsulation

The one we see the most with Closure is keeping a value hidden inside of a function.

function counter(){
let count = 0;

return function incrementCounter(){
count++;
console.log(count);
}
}

3 - Currying

This is more for readability.

function add (a) {
return function (b) {
return a + b;
}
}

add(3)(4) // 7
const addThreeToTotal = add(3);
addThreeToTotal(4); // 7

4 - Memoization

Ah this beautiful word.

tl;dr -

If your function does something performance-heavy, every call will re-create that performance-heavy math every time. Instead, do the performance-heavy math once using closure.

Disadvantages

Some articles say there's a memory inefficicency by creating functions inside functions, but I haven't found proof. Seems like something the V8 Engine would solve.

How Closures Work in JavaScript: A Guide

Closure in JavaScript – Explained with Examples


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.