I have been stuck on this for a couple hours. I tested a recursive function in JavaScript, returned from an if statement but only the function execution context ends and the value I tried to return, was not assigned to the variable. It console.log's as undefined.
Here is my code, it's simple as I'm learning recursive functions:
function foo(i) {
// if i equals 5, return out of function
if (i === 5) {
console.log("We are now at 5");
return "Done";
} else {
console.log(i);
foo(++i);
}
}
let test = foo(0);
console.log(test);
I just simply don't understand why it doesn't return "Done" to the variable, yet if I put the return statement outside of the if/else, it returns how I intend. I tried other regular, simple, non recursive functions and they return fine within the if block.