Mutual recursion in JavaScript

andyrewlee

Andrew Lee

Posted on November 13, 2022

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
💖 💪 🙅 🚩
andyrewlee
Andrew Lee

Posted on November 13, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related