Advertisement
Advanced JavaScript, Functional Programming

What does 'referential transparency' mean, and how does it enable optimizations like memoization?

Short answer

An expression is referentially transparent if it can be replaced with its computed value without changing the program's behavior — true only for pure functions with no side effects.

Save JavaScript mock interview
Advertisement
AModel answer
An expression is referentially transparent if it can be replaced with its computed value without changing the program's behavior — true only for pure functions with no side effects. This property is exactly what makes memoization (caching results by input) safe: you can trust that the same input always deserves the same cached output.
function memoize(fn) {
  const cache = new Map();
  return (arg) => {
    if (cache.has(arg)) return cache.get(arg);
    const result = fn(arg); // safe to cache only if fn is pure
    cache.set(arg, result);
    return result;
  };
}
Real-world example
Memoizing an expensive pure calculation, like a Fibonacci function or a complex pricing formula.
Likely follow-ups
  • Why would memoizing an impure function (one with side effects or external dependencies) be dangerous?
Related topics