Back to stories
<Frontend/>
Premium

Memoization in JavaScript and TypeScript: When and How

Share by

Memoization in JavaScript and TypeScript: When and How

Memoization means caching the result of a function for a given set of arguments and returning the cached value on later calls with the same arguments. It's useful when the function is expensive and called repeatedly with the same inputs. This post explains when to use it, a simple implementation, and when to avoid it.


When memoization helps

  • Expensive pure functions: The same inputs always produce the same output, and the computation is costly (e.g. heavy math, recursive algorithms).
  • Hot paths: The function is called often (e.g. in a render loop or event handler) with repeated arguments.
  • Stable inputs: Arguments are primitives or easily comparable (e.g. serializable) so you can use them as cache keys.

If the function is cheap, called rarely, or almost always with different arguments, memoization adds memory and comparison cost without real benefit.