DEV Community

Understand how to Memoize a JavaScript function

Dhilip kumar on April 26, 2019

What is Memoization anyway? The ability to return the previously calculated value without recalculating them, on receiving same set of...
Collapse
 
logicmason profile image
Mark

I love this. When I was first really digging into JavaScript, I worked through re-implementing everything in Underscore.js and found it super valuable.

_.once and _.memo were pretty hard and really showed how scope and closures were different in JS than I'd realized.

Collapse
 
dhilipkmr profile image
Dhilip kumar

Glad it helped :)

Collapse
 
nickfazzpdx profile image
Nicholas Fazzolari

What would be a potential context/use case for this optimization in the wild?

Collapse
 
dhilipkmr profile image
Dhilip kumar • Edited

The summation function here is so simple. But consider you are making an expensive operation instead of just sum.In that case if you already have a cached value from previous call it becomes handy.

Even react.memo should be doing something similar to this(But handling all limitations which my solution had)

Collapse
 
calag4n profile image
calag4n

It's clever, I love this, nice work dude!

Collapse
 
dhilipkmr profile image
Dhilip kumar

😅✌️✌️