here is my question - can you explain why does this need the 'return' in there?
It has to do with function calls, and how the results of a function are passed back to the caller.
Forget recursion for a moment, and lets look at a pair of functions.
function foo() {
return 'foo for you';
}
function bar() {
foo();
}
What happens if I call bar() like so:
console.log(bar());
Expected output:
'undefined'
foo() is executed, but the results of the functional call are ignored (e.g. not saved to a variable, nor returned). bar() has no explict return statement, so by the ECMA specification, an implicit return undefined; is used.
Looking at the call stack (note that this is written like a stack datastructure with the current function call at the top of the stack):
foo() ==> returns 'foo for you'
bar() ==> returns 'undefined'
Which results in undefined being passed into the console output function.
If we modify bar() like so:
function bar() {
return foo();
}
Our output changes to:
'foo for you'
The result of foo() is returned as the result of bar() examining the call stack
foo() ==> returns 'foo for you'
bar() ==> returns foo() which returns 'foo for you'
Going back to your recursive example, without the return statement, it will execute, but the results of that execution won't be passed up the call stack.
Let's pretend the return statement is missing, and inspect the callstack, when n = 4.
isEven(0) ==> returns true
isEven(2) ==> returns undefined
isEven(4) ==> returns undefined
isEven(4) = undefined. ERROR.
The ultimate expected value, true never gets passed up the callstack.
As written, with the return value, this is the result:
isEven(0) ==> returns true
isEven(2) ==> returns isEven(0) which returns true
isEven(4) ==> returns isEven(2) which returns isEven(0) which returns true
isEven(4) = true PASSED.
n > 1so the function would just returnundefinedinstead oftrueorfalse.