Mutual recursion in JavaScript
Andrew Lee
Posted on November 13, 2022
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);
}
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
isEven(1)
// 1
isEven(1)
// 2
isOdd(0) // => false
isEven(2)
// 1
isEven(2)
// 2
isOdd(1)
// 3
isEven(0) // => true
isEven(3)
// 1
isEven(3)
// 2
isOdd(2)
// 3
isEven(1)
// 4
isOdd(0) // => false
isEven(4)
// 1
isEven(4)
// 2
isOdd(3)
// 3
isEven(2)
// 4
isOdd(1)
// 5
isEven(0) // => true
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
💖 💪 🙅 🚩
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.