简体   繁体   中英

Javascript recursion with return statement and without

Is there a difference between these two recursive functions? One with a return statement and one without it for the recursive calls. They both print numbers 1 - 8 in the console browser, my questions is whether there is some optimization happening under the hood when the recursion takes place with a return vs without one.

 const solution = (input, i = 0) => { if (i === input) return // base case console.log(i) return solution(input, i + 1) // return recursive call } const solution2 = (input, i = 0) => { if (i === input) return // base case console.log(i) solution2(input, i + 1) // recursive call } console.log(solution(4)) console.log("----") console.log(solution2(4))

If the final recursive call doesn't return anything (like in the example in your question), then there's no difference.

If the final recursive call does return something, and you want that to percolate up to the initial caller of solution , then you do need to return the recursive call:

 const solution = (input, i = 0) => { if (i === input) return 'returnVal' // base case return solution(input, i + 1) // return recursive call } const solution2 = (input, i = 0) => { if (i === input) return 'returnVal' // base case solution2(input, i + 1) // recursive call } console.log(solution(9)) console.log("----") console.log(solution2(9))

ES6 does specify that a recursive function whose final action is to return a call to itself should result in the recursive call without growing the call stack. If implemented, this would mean that, for example, a function that recursively calls itself 100,000 times before resolving could run successfully, without overflowing the stack. (Without tail call optimization, such a situation would result in a stack overflow.)

But, unfortunately, as you can see from the link above, despite being part of the specification, it's not widely implemented, so the optimization you're hoping for doesn't exist in practice in most environments.

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