简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM