TIL Javascript Closures
POSTED ON:
TAGS: javascript advanced
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:
- Closure The Basics
- Closure Example with class-like methods
- Closure Example with private data
- Closure Example as a backpack
Related TILs
Tagged: javascript