Home > other >  Why must I put a return in front of a function when using it recursively to get the proper output?
Why must I put a return in front of a function when using it recursively to get the proper output?

Time:10-08

I'm going through the Eloquent Javascript book and one of the exercises is to calculate whether a number is odd or even by creating a recursive function.

My code was this:

function isEven(n) {
  if (n == 0)
    return true;
  else if (n == 1)
    return false;
  else
    isEven(n - 2);
}

When running console.log(isEven(50)); it gives me an output of undefined. Of course the solution is to put a return in front of isEven(n - 2);

Why is that though, shouldn't the function either be returning true or false? How does n become undefined?

CodePudding user response:

Because imagine that you call isEven(3), then isEven(3-1) is called inside of that function and it evaluates to false but you arent returning that value from isEven(3)

CodePudding user response:

Your code, as written, will either:

  1. return true
  2. return false
  3. recursively call itself and, eventually, return undefined because no return statement was triggered

If you want to do something with the value you get from calling the function recursively, then you need to write code to do that thing.

Hence the need to return

CodePudding user response:

Say n = 3. You want your function to return false

There are three calls made to isEven. Each of those calls needs to return something to the thing that called it. From outermost call to innermost call they look like:

output "false" <- return isEven(3) <- return isEven(1) <- return false

  • Related