How is this answer returning an Array!?

Tell us what’s happening:
Hi all,

I’m having trouble understanding how this recursive functions returns an array?
How is it possible for the unshift() method to be called on a declaration like const arr = countdown(n - 1)

if its possible then that means its an array? but i don’t see how???

Your code so far


// Only change code below this line
function countdown(n){
if(n < 1) {
return [];
} else {
const arr = countdown(n - 1);
arr.unshift(n);
return arr;
}
// Only change code above this line

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0.

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

Hey there,

nice to meet you! :wave:

The unshift method is invoked on arr.
arr is the result of countdown(n - 1).

countdown(n - 1) is either:

  • []: when n < 1 (= the base case) or
  • arr: what is again the result of countdown(n - 1) (= every other case)
1 Like

Hey, Thanks for the response. I’m still unsure how arr is an array? it has no syntax such as arr = []? and const arr = countdown(n - 1) is equal to 4? in the question…

also the parameter given to the function is a number not an array?

I feel like i must be missing something so simple… :confounded:

try looking at the code with this tool:

1 Like

You don’t need a direct assignment to become something an array.

function returnArray(){
  return [];
}

const myArray = returnArray();

When you create myArray, it runs the function returnArray.
The function itself returns [], so in the end myArray is [].