Advertisement
Intermediate JavaScript, Functional Programming

Why are recursion and immutable data often used together in functional style, instead of loops with mutable counters?

Short answer

Recursion naturally avoids mutable loop counters and accumulator variables by passing updated state as arguments to each recursive call, keeping each step's data immutable and self-contained — matching the broader functional preference for avoiding shared mutable state.

Save JavaScript mock interview
Advertisement
AModel answer
Recursion naturally avoids mutable loop counters and accumulator variables by passing updated state as arguments to each recursive call, keeping each step's data immutable and self-contained — matching the broader functional preference for avoiding shared mutable state.
function sum(arr, acc = 0) {
  if (arr.length === 0) return acc;
  const [first, ...rest] = arr;
  return sum(rest, acc + first); // no mutable counter
}
sum([1,2,3]); // 6
Real-world example
Processing a linked-list-like or tree-like data structure where a recursive, immutable approach mirrors its shape naturally.
Likely follow-ups
  • What's the risk of using deep recursion in JavaScript, given it lacks guaranteed tail-call optimization?
Related topics