1

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.

1 Answer 1

7

The problem isn't with returning "Done", but with the recursive call. You just call it instead of returning it, so the returned value from the recursive call isn't returned "upwards". Just return it, and you should be OK:

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);
      return foo(++i); // Here!
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Oh ok. I misunderstood the first time. thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.