Getting return undefined on recursive function javascript

前端 未结 4 806
温柔的废话
温柔的废话 2021-01-26 01:58

I heard recursive function is powerful so instead going through loop i tried to create a function which increments a number until it reach certain points. when it reaches i trie

4条回答
  •  北海茫月
    2021-01-26 02:30

    rec will either return i (if i is over 100) or undefined (otherwise).

    When you call it here:

    console.log(rec());
    

    i will be 1 so it will return undefined.

    You never do anything with the return value when the return value is over 100.

    You need to return the result of the recursive call:

    } else {
        return rec();
    }
    

    so when it is over 100, the value gets passed back up the stack.

    it this kind of recursion is good then for loop?

    No. It is horribly inefficient.

提交回复
热议问题