Frontend Interview Logo

How to memoize a function in Javascript?

Topic: Javascript

Difficulty: Medium

How to memoize a function in Javascript?

Clarifying Questions

  • Are you referring to memoizing inside a React component (e.g., useMemo, useCallback), or a general-purpose utility function?
  • Should the function support multiple arguments, including objects and arrays?
  • Should the memoization handle deep equality for arguments, or just reference equality?

Explanation

Memoization is an optimization technique used to cache the results of expensive function calls so that subsequent calls with the same arguments can return the cached result instantly.

Solution Code

Browser Preview
Console Output

Scale-Ups

  • How would you handle caching for deeply nested objects?
  • How would you memoize an async function?
  • How would you add expiration to cached entries?

Interviewer's Expectations

  • Async memoization support
  • Stable and unique key generation and support multiple argument types
#Performance#Javascript