Javascript ES6 recursion function

I wonder how does this recursion function return numbers in this empty array(return n < 1 ? []) without pushing from [n, ...countdown(n - 1)], or how does it push? maybe I don’t understand that es6 syntax

function countdown(n){ return n < 1 ? [] : [n, ...countdown(n - 1)] }

console.log(countdown(5)) log: [5, 4, 3, 2, 1]

Answer

The ...-prefix syntax in this specific context (called the “spread syntax“) puts the elements of the ...-prefixed array directly into the surrounding array.

[ 5, ...[4, 3, 2, 1] ]

is the same as

[5, 4, 3, 2, 1]

That’s just what is happening here. The return values of countdown (from base case up to countdown(5)) look like:

[]
[1, ...[]]             => [1]
[2, ...[1]]            => [2, 1]
[3, ...[2, 1]]         => [3, 2, 1]
[4, ...[3, 2, 1]]      => [4, 3, 2, 1]
[5, ...[4, 3, 2, 1]]   => [5, 4, 3, 2, 1]