Skip to content
Justice Tech School

Recursion Patterns

Recursion solves a problem by calling itself on a smaller one. Every recursive function needs a base case. Deep recursion can overflow the stack, so loops are sometimes safer.

Example
const fact = (n) => (n <= 1 ? 1 : n * fact(n - 1));
const sum = (arr) => (arr.length ? arr[0] + sum(arr.slice(1)) : 0);
console.log(fact(5), sum([1, 2, 3]));
const flat = (a) => a.reduce((r, x) => r.concat(Array.isArray(x) ? flat(x) : x), []);
console.log(flat([1, [2, [3]]]));

Exercise

Stop condition.

The  case stops recursion

Quiz Test

What stops recursion?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.