DEV Community

Cover image for Mutual recursion in JavaScript
Andrew Lee
Andrew Lee

Posted on

Mutual recursion in JavaScript

Mutual recursion is a subset of recursion where a pair of functions are defined in terms of each other.

function isEven(n) {
  if (n === 0) {
    return true;
  }
  return isOdd(n - 1);
}

function isOdd(n) {
  if (n === 0) {
    return true;
  }
  return isEven(n - 1);
}
Enter fullscreen mode Exit fullscreen mode

I didn't realize this was possible until I walked through each function call. Let's walk through the examples step by step:

isEven(0)

// 1
isEven(0) // => true
Enter fullscreen mode Exit fullscreen mode

isEven(1)

// 1
isEven(1)

// 2
isOdd(0) // => false
Enter fullscreen mode Exit fullscreen mode

isEven(2)

// 1
isEven(2)

// 2
isOdd(1)

// 3
isEven(0) // => true
Enter fullscreen mode Exit fullscreen mode

isEven(3)

// 1
isEven(3)

// 2
isOdd(2)

// 3
isEven(1)

// 4
isOdd(0) // => false
Enter fullscreen mode Exit fullscreen mode

isEven(4)

// 1
isEven(4)

// 2
isOdd(3)

// 3
isEven(2)

// 4
isOdd(1)

// 5
isEven(0) // => true
Enter fullscreen mode Exit fullscreen mode

Challenge

Now it's your turn! Try to walk through the following calls:

isOdd(0) // => false
isOdd(1) // => true
isOdd(2) // => false
isOdd(3) // => true
isOdd(4) // => false
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
luiscicada profile image
Ale Guzman • Edited

The previos code is incorrect..

function isEven(n) {
  if (n === 0) {
    return true;
  } else if (n === 1) {
    return false;
  }
  return isEven(n - 2);
}

function isOdd(n) {
  if (n === 0) {
    return false;
  } else if (n === 1) {
    return true;
  }
  return isOdd(n - 2);
}
Enter fullscreen mode Exit fullscreen mode

should be working fine.

Collapse
 
fkereki profile image
Federico Kereki

This is obviously wrong: isOdd(0) === true...