Skip to content
Advertisement

why isn’t recursion working? i am trying to display n to 1 series

Javascript Recursion


why isn’t recursion working here? i see coundown(n-1); isn’t working for some reason. I want to display [5,4,3,2,1]

JavaScript

Advertisement

Answer

Your code creates a new array at every recursive call, puts one value in it and returns it. Nothing is done with the array that is returned, as each execution instance of your function seems only interested in its own array, which it returns.

You need to create one array, and extend that while backtracking out of recursion, each time making sure you capture the array that the recursive call gives you back as return value:

JavaScript

Written a bit more concise it could become:

JavaScript

And without recursion:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement