Is anyone able to explain this to me please?
why with out spread operator?
... it only makes 3 arrays before returning
I assumed the output would be [5,[4,[3,[2,[1,]]]]]
and not [ 5, [ 4, [ 3, [Object] ] ] ]
**Your code so far**
// Only change code below this line
return n < 1 ? 
:[n, countdown(n-1)] ;
// Only change code above this line
**Your browser information:**
User Agent is:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36
Challenge: Use Recursion to Create a Countdown
Link to the challenge:
I think this is just the JS engine using a shortcut instead of printing out all of the subarrays. When I run your code through node it prints
[Array] instead of
[Object] but it’s basically the same thing.
For example, when you pass 5 into your function you technically get:
[ 5, [ 4, [ 3, [ 2, [ 1,  ] ] ] ] ]
But instead of printing all of those out the JS engine only prints the three most outer arrays and then uses a shortcut for the rest (either
[Object]). If I modify your function to put the results of the recursion in a variable and then JSON.stringfy() the variable when logging it then it prints all of the subarrays without using the shortcut.
Regardless, your function isn’t quite giving the correct answer, but when it does you will not run into this problem.
Thanks for that.
I’m still learning so when something unexpected happens like to know why .
So I appreciate your explanation.
To be honest, I didn’t know what was going on initially either, so I had to play around with it a little to figure it out. I’m still not 100% certain my explanation is totally correct but it seems pretty plausible.
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.