climboid
climboid

Reputation: 6962

Recursive method in javascript always returns undefined instead of true,

Why does the following method always return undefined? Event though the log in the console says true?

var x = [1,2,3,4,5];
var y = 9;


function addUp (x, y) {
  for (var i=0, j=1; j < x.length; j++) {
    if (x[i] + x[j] === y) {
      console.log("in here result should be true");
      var result = true;
      break;
    }
   }

  console.log("len", x.length, "result",result);
  if ((!result) && (x.length > 2)) {
    console.log("recursively calling");
    addUp(x.slice(i+1, x.length), y)
  } else if(result) {
    console.log("in the if why doesn't this return true?")
    return true;
  } else {
    return false;
  }
}

addUp(x,y);

Upvotes: 0

Views: 39

Answers (2)

Shomz
Shomz

Reputation: 37701

You probably want to return the result of recursive calls:

return addUp(x.slice(i+1, x.length), y)

instead of just:

addUp(x.slice(i+1, x.length), y)

Upvotes: 2

Nico
Nico

Reputation: 12683

The problem is in your first if statement

console.log("len", x.length, "result",result);
  if ((!result) && (x.length > 2)) {
    console.log("recursively calling");
    addUp(x.slice(i+1, x.length), y)
  } else if(result) {
    console.log("in the if why doesn't this return true?")
    return true;
  } else {
    return false;
  }

You will see that the if ((!result) && (x.length > 2)) { does not return anything. Therefore if this match is found the following next two else statements will not be executed.

You should provide either a return statement in the first if statement or put a final return at the end of the method.

Upvotes: 0

Related Questions