JavaScript › Functional Programming
Why are recursion and immutable data often used together in functional style, instead of loops with mutable counters?
IntermediateAnswer
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]); // 6Real-world example Processing a linked-list-like or tree-like data structure where a recursive, immutable approach mirrors its shape naturally.