Go to Home

Memoization in Javascript

In continuation with my previous articles on discussing about the programming techniques on Javascript, Today, I would like to explain about a simple technique called Memoization.

In computing, memoization or memoisation is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again - Wikipedia

To put it in simple terms, a function with the same set of inputs should always return the same result without really performing computation after the first time. Let me explain you with an example.

Assume you wanted to extract the in_stock items from the list of cart items. So, you would be performing something like the following

At first, this might seem like a simple and easy solution. But if you look deeply, we've a problem here. Every time we call inStock() method, we'll be receiving new object which means, even though we're calling the inStock() with the same arguments, it'll be performing the filtration and return us the new items every single time.

Programming like this is bad and functions like this could quickly turn into ugly, more time consuming ones to compute had we have a long list of arguments. So, let's implement memoization here


Reselect is basically a package developed by redux team and it was initially used only within the redux projects. However, as mentioned in their documentation, reselect has no dependencies on any other package, it can be used independently outside of redux. So, let's apply reselect on our above example and fix the issue

That's it! With help of reselect, no matter how many times you called inStock() function it'll always return the same result. That's the beauty of reselect! Programmatically, we can even call our inStock() function as a pure function since the result is always going to be same for same set of input. With this, we can easily avoid recomputation of our logic and improve efficiency of our code.

Happy Coding!

One email per week. No spam ever.