# Basic JavaScript - Use Recursion to Create a Countdown

Hi could someone please explain to me how does the unshift function works in this recursion I really dont understand. I’ve watched countless videos and read articles I cant see to grasp how and why it adds the number 5 at the beginning.

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

}

}
// Only change code above this line
console.log(countdown(5));
``````

User Agent is: `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36`

Challenge: Basic JavaScript - Use Recursion to Create a Countdown

Are you saying you don’t know what the `unshift` method does? Is so, how were you able to solve this?

If you know what the `unshift` method does then you should know why it adds the number `n` to the beginning of the array `x`.

i know its the opposite of push

I’m assuming you understand that `push` adds an element to the end an array. So then `unshift` adds an element to the beginning of an array.

Thus, if your initial function call is:

``````countdown(5)
``````

Then the `else` block will be executed, and `n` being equal to `5` will give you:

``````  const x = countdown(4);
x.unshift(5);
return x
``````

Since `countdown` always returns an array, then `x` will be an array and thus `x.unshift(5)` will add `5` to the beginning the array stored in `x`. Thus, `5` will be at the beginning of the array that is returned.

1 Like

thank u I think my brain was fried yesterday it makes sense now