1

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]

1
  • You should indeed just read what the spread operator does. PS: The function is not a good way to generate that desired result. Try e.g. countdown(20000) vs Array.from({ length: 20000 }, (_, i) => 20000 - i), but i guess its purpose is to showcase ES6 features? Commented Nov 6, 2020 at 18:06

2 Answers 2

3

The call stack steps that produce the result:

1. n = 5 => [5, ...countdown(4)]
2. n = 4 => [5, 4, ...countdown(3)]]
3. n = 3 => [5, 4, 3, ...countdown(2)]]
4. n = 2 => [5, 4, 3, 2, ...countdown(1)]
5. n = 1 => [5, 4, 3, 2, 1, ...countdown(0)]
6. n = 0 => [5, 4, 3, 2, 1, ...[]]

So the ... is spreading syntax notation that works like concat for two arrays.

Another schema could be like:

1. n = 5 => [5, ...countdown(4)]
2. n = 4 => [5, ...[4, ...countdown(3)]]
3. n = 3 => [5, ...[4, ...[3, ...countdown(2)]]]
4. n = 2 => [5, ...[4, ...[3, ..[2, ...countdown(1)]]]]
5. n = 1 => [5, ...[4, ...[3, ...[2, ...[1, ...countdown(0)]]]]]
6. n = 0 => [5, ...[4, ...[3, ...[2, ...[1, ...[]]]]]]

Think about that like function call stack from left to right:

x1( x2( x3() ) ) => ...( ...( ...(n) ) )
Sign up to request clarification or add additional context in comments.

2 Comments

Do you mean this? 1. n = 5 => [5, ...countdown(4)] 2. n = 4 => [5, [4, ...countdown(3)]] 3. n = 3 => [5, [4, [3, ...countdown(2)]]] 4. n = 2 => [5, [4, [3, [2, ...countdown(1)]]]] 5. n = 1 => [5, [4, [3, [2, [1, ...countdown(0)]]]]] 6. n = 0 => [5, [4, [3, [2, [1, ...[]]]]]]
The next call will return [n, ...countdown(n-1)] so the result of each call is an array and the return value will be concatinated with last one by spreading syntax nottion (...)
3

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.