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

前端 未结 6 372
旧时难觅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:26

    When using the function without the second return statement, the function yields no value to the callee per definition in JavaScript returns undefined.

    So using the first definition and for example loop(9):

    1. 0 < 10, so we don't execute the if-clause body, but just call loop(10).
    2. loop(10) returns 10, but we never use this value.
    3. the function loop ends and, as no other value was returned, it returns undefined.

提交回复
热议问题