Recursion defines a computation through calls to that same computation. It is especially useful for nested data, where the function’s structure can mirror the data’s structure while the call stack remembers where to continue. section 14.18 section 14.23
Make recursive functions safe by checking three conditions:
- Write a base case that performs no recursive call and clearly stops the process. section 14.16
- Provide a recursive case where the function calls itself. section 14.16
- Move at least one argument closer to the base case on every call; repeating the same arguments creates an infinite loop. section 14.16
Array loops process elements in sequence, but nested operations get values while descending, modify the final value, and set copies while returning upward. Recursion and the call stack support this matching structure. Loops can be clearer in many cases; recursion becomes clearer when data is nested arbitrarily deeply. section 14.18 section 14.23
Updating a value through a nested path
A nestedUpdate() function stops when its key path is empty; otherwise, it removes the first key and recursively updates the remaining path. For example, incrementSizeByName(cart, name) can update [name, 'options', 'size'] by applying a size + 1 modification at the destination. section 14.18 section 14.16
function nestedUpdate(object, keys, modify) {
if(keys.length === 0)
return modify(object); #1
var key1 = keys[0];
var restOfKeys = drop_first(keys);
return update(object, key1, function(value1) {
return nestedUpdate(value1, restOfKeys, modify);
});
}
Inspect the nestedUpdate() implementation to see the empty-path base case, the shortened key path, and the recursive call inside update(). section 14.16






















