i tried to write this function for guessing if a given number is even or not using recursion, This is my code :
function isEven(N){
if(N===0){
return true;
}else if(N===1){
return false;
}else {
isEven(N-2);
}
}
console.log(isEven(1)); // gives false
console.log(isEven(0)); //gives true
console.log(isEven(10)); // gives undefined
I dont know why the function is not working except for 0 and 1.
returnstatement beforeisEven(N-2)n % 2 === 0? I understand recursion is misapplied for pedagogical purposes, but this is beyond my comprehension. In addition to the solution given (usereturnon all cases), this will blow the stack on negative numbers.const isOdd = (n) => n < 1 ? false : isEven (n -1), etc.) It's not always easy to demonstrate the power of mutual recursion, but this one is usually instantly clear.