0

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.

6
  • 6
    You forgot a return statement before isEven(N-2) Commented Aug 17, 2021 at 21:20
  • 1
    Welcome to SO! Why not n % 2 === 0? I understand recursion is misapplied for pedagogical purposes, but this is beyond my comprehension. In addition to the solution given (use return on all cases), this will blow the stack on negative numbers. Commented Aug 17, 2021 at 21:20
  • @ggorlen: It will also blow the stack with a relatively small positive number, but the point is, as you note, entirely pedagogical. Starting from this, we can make simple changes to demonstrate a mutually recursive solution (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. Commented Aug 17, 2021 at 23:04
  • @ScottSauyet Good point, yes, this is virtually useless on positive numbers too. I've probably used mutual recursion 2-3 times. The problem with entirely pedagogical examples is that entire curricula are "entirely pedagogical" and students wind up having no idea which tool to apply to which problem, which is pretty much 95% of being a successful programmer. Not a rant at you and I'm sure you're aware, but the recursion tag is loaded with hapless students trying to smash nails with screwdrivers because they have to... Commented Aug 17, 2021 at 23:15
  • @ggorlen: Our experiences are quite different. I find myself using recursion often in my day-to-day JS coding. It's often the simplest, most understandable version of a solution; if it's ill-performant for my task, I'll refactor later. While mutual recursion is less common, it is far from rare. I agree that programmers' education should be designed to showcase the tools and techniques students will need, but I have no problem with assignments like this if they help demonstrate such techniques. And no, I didn't feel a rant aimed at me, and I hope you don't either. Just different experiences. Commented Aug 18, 2021 at 11:42

1 Answer 1

-2

Because the isEven() funtion enters a loop and cannot send anything to the output. Try to change your function and write it in other way

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.