Simple Recursive Javascript Function Returns Undefined

前端 未结 2 584
梦谈多话
梦谈多话 2021-01-20 23:24

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 undefine

相关标签:
2条回答
  • 2021-01-21 00:08

    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));

    0 讨论(0)
  • 2021-01-21 00:22

    You can change the following line:

    isEven(num);
    

    to

    return isEven(num);
    
    0 讨论(0)
提交回复
热议问题