Why return in this code?

This question is not about the course, although I am taking it. In Elegant Javascript, there is an exercise that gave me trouble. I only got the answer by sort of copying an earlier example, but I don’t know why it works. Hopefully someone can explain.

Basically, the idea is to test whether a given number is even or odd using the following concepts: 1 is odd, 0 is even, for any other number, n, the evenness is the same as n-2.

I translated that into the following:

function isEven(number) {
if (number == 0) {
return true;
} else if (number == 1) {
return false;
} else {
isEven(number-2); //recursively calls the function on number-2; eventually, we’ll get down to 0 or 1 and get a true or false.
}
};

which doesn’t work. But what works is only one word different. It uses “return” for the else code-block:

function isEven(number) {
if (number == 0) {
return true;
} else if (number == 1) {
return false;
} else {
return isEven(number-2); //“return” makes all the difference
}
};

I don’t understand why you need the return. Wouldn’t calling the function eventually result in a return of either true or false above?

Hello, @migueldemaria0134906.

Recursion can be tricky to understand. Consider what this line at the end of the function is/does. Don’t think about it as part of the isEven() function, but all by itself.

isEven(number-2)

It’s simply a function call. Its location in the code doesn’t give it any special powers that it doesn’t have anywhere else. With that in mind, when the value of number eventually gets to either 1 or 0, consider where true or false gets returned to.

1 Like

Thanks, I think I’m starting to get it. The “return” of the recursive true or false code has to return to something. Once we go into the recursion, that something is this part of the code, which is what eventually returns the code to the original call. Is that sort of it?

Just like any other function call, the return value goes to the line of code that called the function. In your first example once the value is returned to the caller inside the function, nothing else happens to it. Adding return to the beginning of that line, returns the value to the original caller.

1 Like