Functional programming: Closures and Memoization in JavaScript

The goal of this post is to explain how to implement closures and memoization in JavaScript. I learn better when I code and if you’re like me, then you will surely enjoy this article.

Sample JavaScript image
Photo by Irvan Smith on Unsplash
function addTo80(num) {
return num + 80;
}
console.log(addTo80(5)); // Computes and returns 85
console.log(addTo80(5)); // Computes and returns 85
console.log(addTo80(5)); // Computes and returns 85
Output:
85
85
85
function addTo80(num) {
return num + 80;
}
let cache = {};
function memoizedAddTo80(num) {
if (num in cache) {
return cache[num];
} else {
console.log('Calculating...');
cache[num] = num + 80;
return cache[num];
}
}
// Computes and stores 85 in cache
console.log(memoizedAddTo80(5));
// Returns memoized data from memory
console.log(memoizedAddTo80(5));
// Returns memoized data from memory
console.log(memoizedAddTo80(5));
// Output:
Calculating...
85
85
85
cache: {
5: 85
}
  1. Where are the closures being used?
function addTo80(num) {
return num + 80;
}
function memoizedAddTo80() {
let cache = {};
return function(num) {
if (num in cache) {
return cache[num];
} else {
console.log('Calculating...');
cache[num] = num + 80;
return cache[num];
}
}
}
const memoized = memoizedAddTo80();// Computes and stores 85 in cache
console.log(memoized(5));
// Returns memoized data from memory
console.log(memoized(5));
// Returns memoized data from memory
console.log(memoized(5));
// Output:
Calculating...
85
85
85
return function(num) {
if (num in cache) {
return cache[num];
} else {
console.log('Calculating...');
cache[num] = num + 80;
return cache[num];
}
}

Front end developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store