SpinSpire logo

Closures

What is a closure?

function food() {
// outer scope
let favoriteFood = "Tacos";
function drink() {
// inner scope
console.log(favoriteFood); // => Tacos
}
drink();
}
food();

Common use case for closures

  1. Giving a function access to data without exposing that data to the rest of your code, creating partially applied functions.
  1. 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
console.log(balance.show()); // 300 *notice it isn't 0*

References:
  1. Closures
  2. Closure Examples