Back to results for “OOP”
JavaScript › Functional Programming

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

Intermediate

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.

Common follow-ups: What's the risk of using deep recursion in JavaScript, given it lacks guaranteed tail-call optimization?