Memoization Explained, Using JavaScript

Ryan Sperzel
2 min readJan 7, 2018

--

I think every programmer has heard this word before and been like, “memorization”? Memoization isn’t quite that, but it’s actually very close to it. I always think of memoization as the computer ‘memorizing’ values. So what is it actually then? Memoization is a programming technique that ensures a function doesn’t run using the same inputs more than once. How, and why, does it do that? Memoization essentially attempts to optimize a function’s performance by caching its previously computed results. Why do we care about a function running multiple times? Well, if a function looks something like this:

function multiplyByTwo(number) {
return number * 2
}

then memoization might not be necessary. In this function, we provide one argument, a number, and the function will return the product of that number and 2. It’s not going to take the computer very long to run this function, no matter what the input is. But we can still use memoization if we want to! Let’s take a look at how it might work here:

function multiplyByTwo(number) {
if (!multiplyByTwo.cache[number]) {
let result = number * 2
multiplyByTwo.cache[number] = result
}
return multiplyByTwo.cache[number]
}
multiplyByTwo.cache = {}

So what’s going on? I think the first thing we need to assert is that all functions in JavaScript are objects — they can have methods and properties like any other JS object. We give our multiplyByTwo function a cache property on the last line — an empty object. What does the function do when it’s called? Let’s say we call it with 10 as the argument. The first thing it does is check if its cache property (an empty object) has a key of the number inputted (10). If not, it creates a variable result and sets it to the product of the number input and 2. It then creates a key on the cache property of the inputted number with its value set to result. Lastly, it returns the value of that key.

What happens when we don’t hit that if statement — aka when multiplyByTwo.cache[number] is truthy? For example, what if we run the function with the input of 10 again? Well, multiplyByTwo.cache[number] already exists — its value is 20. It simply returns that number, preventing the function from having to run with an input it has already run before.

Pretty cool, huh? It may not affect performance too much in this example, but there are a lot of cases where memoization can make a function a lot faster. Next week, we’ll supplement this post with a more practical example — using a popular technical interview question! Keep an eye out for it!

--

--