Belajar
← All lessons

How recursion works

Push frames down, unwind back up

Call stack

factorial.js

function factorial(n) {  if (n <= 1) return 1; // base case: stop recursing  // this frame waits here until the call returns  const rest = factorial(n - 1);  return n * rest;} const answer = factorial(4);

Get the base case wrong and it never stops

countdown(n), n =Base casen <= 0n === 0NoneEach call passesn - 1n - 2
First calls
deepest frame

countdown.js

function countdown(n) {  if (n <= 0) return 0;  if (n === 0) return 0;  return 1 + countdown(n - step);}

Run out of stack for real, in this tab

sumTo(n), n =
Written asRecursionLoop
frames at the deepest point
this browser's limit
result

Every engine sets its own limit, so code that recurses once per item breaks on big inputs

sum-to.js

function sumTo(n) {  if (n <= 0) return 0;  // one frame per number still on the stack  return n + sumTo(n - 1);} function sumToLoop(n) {  let total = 0; // no new frames, just one variable  for (let k = 1; k <= n; k++) total += k;  return total;}

Topics

Next: How graph search works

Open lesson