ekcoder
ekcoder

Reputation: 23

Can't return a value within if statement in JavaScript

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.

Upvotes: 1

Views: 1559

Answers (1)

Mureinik
Mureinik

Reputation: 311823

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!
   }
}

Upvotes: 7

Related Questions