3

For an assignment I am supposed to write a recursive function that checks any integer for even or odd using N-2. If even returns true else returns false. But it returns undefined whenever a value is large enough to call itself. Please help!

function isEven(num) {
  console.log("top of function num = " + num);// For Debugging
  if (num == 0){
      return true;
  }
  else if (num == 1){
      return false;
  }
  else {
    num -= 2;
    console.log("num = " + num);
    isEven(num);
  }
}
console.log(isEven(0));
// → true
console.log(isEven(1));
// → false
console.log(isEven(8));
// → ??

Console Log Results:

top of function num = 0

true

top of function num = 1

false

top of function num = 8

num = 6

top of function num = 6

num = 4

top of function num = 4

num = 2

top of function num = 2

num = 0

top of function num = 0

undefined
4
  • 2
    Your else case in isEven never returns a value. Commented Nov 14, 2016 at 12:06
  • 1
    The else really does need to return a value! Commented Nov 14, 2016 at 12:12
  • 1
    Great, homework teaching you the wrong ways to use a recursive function. Use modulus instead. Commented Nov 14, 2016 at 12:30
  • 3
    @Xorifelse The point is to become comfortable writing recursive functions, not to write an efficient test of whether a number is even. Commented Nov 14, 2016 at 12:45

2 Answers 2

4

You have forgotten the return statement before the recursive isEven(num) call.

See the snippet below:

function isEven(num) {
  //console.log("top of function num = " + num);// For Debugging
  if (num == 0){
      return true;
  }
  else if (num == 1){
      return false;
  }
  else {
    num -= 2;
    return isEven(num);
  }
}
console.log('0 is even: ', isEven(0));
// → true
console.log('1 is even: ', isEven(1));
// → false
console.log('8 is even: ', isEven(8));

Sign up to request clarification or add additional context in comments.

4 Comments

Oh, @cyber_rookie seems to have beaten me to it. Really unsure why we both got -1'd though, our answer is most certainly correct!
Excellent! Would you be so kind to mark the answer as the answer?
Thanks for the reminder and once again thank you so much for the fix.
Use the snippet button in the button bar when typing an answer :) (Ctrl+M also seems to do it on Windows)
0

You can change the following line:

isEven(num);

to

return isEven(num);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.