TIL Why use Closures
POSTED ON:
TAGS: javascript freecodecamp advanced
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 #
- Variables inside closures can't be garbage-collected.
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: javascript