Today I Learned - Rocky Kev

TIL Javascript Closures

POSTED ON:

TAGS:

This is based on this question:

Make this syntax possible:
#1 - var a = add(2, 3); //5
#2 - var a = add(2)(3); //5

#1's Answer:
var a = add(2, 3); //5

// CLASSIC JS
function add(x, y) {
return x + y;
}

// ARROW FUNCTIONS
const add = (x, y) => x + y;

#2's Answer:
var a = add(2)(3); //5

// CLASSIC JS
var add = function(x) {
return function(y) {
return x + y;
};
}

// ARROW FUNCTIONS
const add = x => y => x + y;

So what the heck is happening here?
Using a mental model (and this is is for humans to understand visually what is going on) --

Functions are simply labels. Behind the scenes, the code will replace the label with the body of the function.

Using this again:
var a = add(2)(3);

// Taking the params (2) and (3)
// The original function
var add = function() {
x = 2;
y = 3;
return function(y) {
return x + y;
};
}
// broken down even more
var x = 2;
return function(3) {
return x + 3;
}

This is at a very basic level, and allows you to nestle functions and params.

Closure is the basis of a lot of other tricks for code organization, which I'll share in a few other posts.

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.