I'm just getting my head around recursion in javascript using the book Eloquent Javascript but don't fully understand what is happening to the negative number (-1) in this fiddle:
http://jsfiddle.net/greenhulk01/kg5ton1t/
function isEven(n) {
if (n == 0) {
return true;
} else if (n == 1) {
return false;
} else if (n < 0) {
return isEven(-n);
} else {
return isEven(n - 2);
}
};
console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-1));
// → false
I understand everything that is going on in this recursion except for how "return isEven(-n);" is being handled. Using console.log i can see it is returned as undefined so not sure why it is caught by the false statement.
Any pointers to help my understanding would be really appreciated.
Cheers.
See Question&Answers more detail:os