Emmanuel Akinfulubi

JavaScriptRecursion

Even or odd using recursion in JavaScript

Intermediate · 3 min read

Checking whether a number is even is normally one line: n % 2 === 0. So why write it with recursion? Because this exercise teaches mutual recursion, where two functions call each other back and forth. That pattern is real: it powers the parsers that read code, math and file formats. Even and odd is the smallest example of it you can find.

In this tutorial you will write isEven and isOdd without using %, make them handle negative numbers, and then find out exactly why you should never ship them. You need to know what a function is. Recursion is explained below.

The idea in plain words

Forget division for a moment. You can decide whether a number is even just by counting down:

  • 0 is even.
  • A number is even if the number one below it is odd.
  • A number is odd if the number one below it is even.

So 3 is odd because 2 is even, because 1 is odd, because 0 is even. Each answer leans on the one below it, until you reach 0, which you simply know. That stopping point is called the base case.

What is mutual recursion?

A recursive function calls itself. With mutual recursion, function A calls function B, and B calls A. Here, isEven asks isOdd about the number below, and isOdd asks isEven. Each function's base case is the 0 check.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

7 Even or odd, recursively

fair

Decide whether a number is even without using %, by having "is it even" and "is it odd" call each other. Then work out why you should not ship it.

Stuck? Three hints, smallest first
  1. 1. isEven(0) is true; otherwise the answer is isOdd(n - 1).
  2. 2. Take the absolute value first, or negative inputs count downwards forever.
  3. 3. Every step down is a stack frame, so a large number will overflow the stack.

Step 1: two functions that call each other

Step 1

function isEven(n) {
  return n === 0 ? true : isOdd(n - 1);
}
function isOdd(n) {
  return n === 0 ? false : isEven(n - 1);
}
console.log(isEven(10)); // true
console.log(isOdd(7));   // true
console.log(isEven(0));  // true

Follow isOdd(2): it asks isEven(1), which asks isOdd(0). That is 0, and isOdd says 0 is not odd, so the answer false travels back up. 2 is not odd.

JavaScript lets isEven call isOdd before isOdd is written below it, because function declarations are set up before any code runs.

Step 2: the negative number trap

Try a negative number with Step 1's functions:

JavaScript

function isEven(n) {
  return n === 0 ? true : isOdd(n - 1);
}
function isOdd(n) {
  return n === 0 ? false : isEven(n - 1);
}
try {
  isEven(-4);
} catch (e) {
  console.log(e.constructor.name); // 'RangeError'
}

-4 counts down to -5, -6, -7 and never reaches 0. The calls pile up until JavaScript throws RangeError: Maximum call stack size exceeded. Whether a number is even doesn't depend on its sign, so take Math.abs first, which removes the minus sign:

Step 2

function isEven(n) {
  n = Math.abs(n);
  return n === 0 ? true : isOdd(n - 1);
}
function isOdd(n) {
  n = Math.abs(n);
  return n === 0 ? false : isEven(n - 1);
}
console.log(isEven(-4)); // true
console.log(isOdd(-7));  // true

Step 3: check it against %

The % operator gives the remainder after dividing. An even number has remainder 0 when divided by 2. Use it to check the recursive version:

Step 3

function isEven(n) {
  n = Math.abs(n);
  return n === 0 ? true : isOdd(n - 1);
}
function isOdd(n) {
  n = Math.abs(n);
  return n === 0 ? false : isEven(n - 1);
}
const isEvenFast = (n) => n % 2 === 0;
const agree = Array.from({ length: 61 }, (_, i) => isEven(i) === isEvenFast(i)).every(Boolean);
console.log(agree); // true

Array.from({ length: 61 }, ...) runs the comparison for 0 to 60, and every(Boolean) is true only if all 61 comparisons are true.

Step 4: why you should not ship it

Every step down is a function call that has to wait for the next one. JavaScript keeps those waiting calls on the call stack, and the stack has a size limit. A big number goes past it:

Step 4

function isEven(n) {
  n = Math.abs(n);
  return n === 0 ? true : isOdd(n - 1);
}
function isOdd(n) {
  n = Math.abs(n);
  return n === 0 ? false : isEven(n - 1);
}
const isEvenFast = (n) => n % 2 === 0;
try {
  isEven(1e6);
} catch (e) {
  console.log(e.constructor.name); // 'RangeError'
}
console.log(isEvenFast(1e6)); // true

1e6 is a million. The recursive version would need a million waiting calls and crashes. The % version answers instantly, for any size. Use recursion here to learn the pattern, and % in real code.

The full solution

The panel has the mutually recursive pair, the % version, and checks for 0, negatives, agreement with %, and the crash on a million. Press Run to see the output.

The answer

// Mutual recursion: each function's base case is the other's exit.
function isEven(n) {
  n = Math.abs(n);
  return n === 0 ? true : isOdd(n - 1);
}
function isOdd(n) {
  n = Math.abs(n);
  return n === 0 ? false : isEven(n - 1);
}

// What you would actually write. Constant time, no stack, no limit.
const isEvenFast = (n) => n % 2 === 0;

// Prove the limit rather than assert it in a comment.
const overflowed = (() => {
  try { isEven(1e6); return 'no error'; } catch (e) { return e.constructor.name; }
})();

console.log('isEven(10) :', isEven(10));
console.log('isOdd(7)   :', isOdd(7));
console.log('isEven(0)  :', isEven(0));
console.log('isEven(1e6):', overflowed, '<- one stack frame per step down');
console.log('isEvenFast(1e6):', isEvenFast(1e6), '<- no recursion, no limit');

Output


      
11 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 11 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

11 checks

test('10 is even', isEven(10), true);
test('7 is not', isEven(7), false);
test('0 is even', isEven(0), true);
test('1 is odd', isOdd(1), true);
test('7 is odd', isOdd(7), true);
test('even and odd always disagree', Array.from({ length: 30 }, (_, i) => isEven(i) !== isOdd(i)).every(Boolean), true);
test('negatives follow the same rule', isEven(-4), true);
test('and -7 is odd', isOdd(-7), true);
test('it agrees with % for 0 to 60', Array.from({ length: 61 }, (_, i) => isEven(i) === isEvenFast(i)).every(Boolean), true);
test('a million overflows the stack', overflowed, 'RangeError');
test('the % version handles it instantly', isEvenFast(1e6), true);

Worth being blunt: this is a bad way to test for evenness. n % 2 === 0 is one machine instruction; the recursion is a million function calls that ends in a RangeError, and the assertion above catches that error to prove it. The exercise is still worth doing, because mutual recursion — two functions whose base cases are each other's — is a real pattern. It turns up in parsers, where "parse an expression" and "parse a term" call back and forth. Just not here.

Common mistakes

  • Forgetting negatives. Without Math.abs, any negative input counts down forever and throws a RangeError.
  • Giving both functions the same base case answer. isEven(0) is true and isOdd(0) is false. Swap them and every answer flips.
  • Using this in real code. It needs one call per number, so large inputs crash. n % 2 === 0 has no limit.

Try it yourself

  1. Add a counter and check that isEven(10) makes 11 calls in total across both functions.
  2. Write isMultipleOf3(n) the same way with three functions, for remainders 0, 1 and 2.
  3. Find roughly the largest number isEven can handle in your browser before it throws. Try 5,000, then 10,000, and so on.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.