How does using a return clause before a recursive function call differ from not using one?

前端 未结 6 425
旧时难觅i
旧时难觅i 2021-01-25 09:39

I was just experimenting with some recursion and noticed something that confused me. Let me illustrate with some code examples:

function loop(x) {
  if (x >=          


        
6条回答
  •  自闭症患者
    2021-01-25 10:15

    If you don't return from a Javascript function there is an implicit "return undefined" in the end.

    function loop(x) {
      if (x >= 10)
        return x;
      loop(x + 1); // the recursive call
      return undefined;
    }
    

    As you can see, te recursive call is being called and having its return value ignored. This is just like what happens when you call a function like console.log - the function gets called and runs any side-effects but you discard the return value in the end.

提交回复
热议问题