Red Pill Reality
Red Pill Reality

Reputation: 35

Javascript function returns undefined when the value is clearly set

Very simple but... Weird The value of b is clearly settled as you can see on the console but it returns undefined.

function loopMe(n,b){
  b++;
  console.log(n+' '+b);
  if(n===0){
    return b
  }
  loopMe(--n,b);
}

console.log(loopMe(5,3));

You can clearly see the value of b within the function so why it's not returning it?

Why is that?

Upvotes: 0

Views: 38

Answers (1)

Nick
Nick

Reputation: 16586

You are simply forgetting to return your recursive call to loopMe.

function loopMe(n,b){
  b++;
  console.log(n+' '+b);
  if(n===0){
    return b
  }
  return loopMe(--n,b);
}

console.log(loopMe(5,3));

Upvotes: 2

Related Questions