Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
168 views
Welcome To Ask or Share your Answers For Others

1 Answer

isEven(-n) just takes advantage of the fact that if -n is even, n is even, too. So basically isEven(-10) calls isEven(10)

BTW: Did you try isEven(1.5)? I'd expect false, but I'd guess you'd get a stack overflow. I'd write this as

function isEven(n) {
  if (n < 0) {
    return isEven(-n);
  }
  if (n >= 2) {
    return isEven(n - 2);
  }
  return n == 0;
}; 

BTW 2: Without using recursion, you could just write

function isEven(n) {
  return n % 2 == 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...