Closures
What is a closure?
Like previously discussed, JS variables can be either local or global scoped.
A closure is a function that has access to an outer function’s scope. The ‘outer’ scope of a function which is defined inside a closure is called the lexical scope.
function food() {
let favoriteFood = "Tacos";
function drink() {
console.log(favoriteFood); // => Tacos
}
drink();
}
food();
The inner function has access to the outer scope’s variables. A closure is a function that exists outside of the scope it was defined in, that is holding access to a variable from that scope.
Common use cases
- Giving a function access to data without exposing that data to the rest of your code, creating partially applied functions.
- Increasing code reusability by providing custom function generators.
Examples
function outer() {
let x = 3
return function inner(y) {
return x*y
}
}
let multiplyByThree = outer();
console.log(multiplyByThree(2));
// displays 6
function number() {
let a = 4;
function numberExample() {
console.log(a);
}
return numberExample;
}
let id = number();
id();
function wait(message) {
setTimeout(function timer() {
alert(message);
}, 1000);
}
wait("This is a closure example!");
const balance = (function() {
let privateBalance = 0;
return {
increment: function(value) { privateBalance += value; return privateBalance; },
decrement: function(value) { privateBalance -= value; return privateBalance; },
show: function() { return privateBalance; }
};
})()
console.log(balance.show()); // 0
console.log(balance.increment(500)); // 500
console.log(balance.decrement(200)); // 300