Originally published on php-to-js.learnio.dev — part of the PHP to JavaScript course. View this lesson on the original site.

Recursion is a function that calls itself

PHP and JavaScript both support recursion: a function solves a smaller version of the same problem until a base case stops the chain. The engine keeps each call on the call stack — too many levels and you get a stack overflow.

PHP habit

<?php
function sumArray(array $items): int {
    if ($items === []) {
        return 0;
    }
    return array_shift($items) + sumArray($items);
}

function factorial(int $n): int {
    if ($n <= 1) {
        return 1;
    }
    return $n * factorial($n - 1);
}
// Iterative equivalent — often clearer for large lists
function sumArrayLoop(array $items): int {
    $total = 0;
    foreach ($items as $item) {
        $total += $item;
    }
    return $total;
}

JavaScript equivalent

function sumArray(items) {
  if (items.length === 0) return 0;
  const [head, ...tail] = items;
  return head + sumArray(tail);
}

function factorial(n) {
  if (n <= 1) return 1;
  return n * factorial(n - 1);
}
Topic PHP JavaScript
Base case if ($n <= 1) return 1 if (n <= 1) return 1
Recursive step return $n * factorial($n - 1) return n * factorial(n - 1)
Stack limit Maximum function nesting level / memory RangeError: Maximum call stack size exceeded

When recursion fits

Tree walks, nested comments, or problems defined recursively on paper. For flat arrays in app code, for or reduce is usually simpler and safer on the stack.

Failure mode: missing base case

Without a stop condition, recursion never ends until the stack blows up. Always define the smallest input that returns without calling itself again.

Try it

Use the amber Try it panel below. Click Run.

console.log('factorial(5)', factorial(5));
console.log('sumArray', sumArray([1, 2, 3, 4]));

function countdown(n) {
  if (n === 0) return 'done';
  return `${n}, ${countdown(n - 1)}`;
}
console.log(countdown(3));

Expect factorial(5) 120, sumArray 10, and a string ending in done.

From PHP to JavaScript — Control Flow, Functions, and Scope