Is anyone able to explain this to me please?
why with out spread operator? ... it only makes 3 arrays before returning [Object]
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
function countdown(n){
return n < 1 ? []
:[n, countdown(n-1)] ;
}
// Only change code above this line
console.log(countdown(5));
**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
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 [Array] or [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.
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.