Search code examples
javascripthtmlfunctionreturn

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?


Solution

  • 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));