0

guys can someone explain what ([head, ...[headTail, ...tailTail]]) in the input of this link solution is doing? I can't comment and ask the writer due to low reputation!

he is writing a function that takes an array of arrays in input (based on where he calls it) but although I know few things about rest and spread in Java Script I cant figure this out!

1
  • FYI: this peace of code ([head, ...[headTail, ...tailTail]]) smells. Commented Dec 13, 2020 at 7:59

2 Answers 2

2

As Lex82 correctly answered, this is a way to destructure an array. So, if you have

const [head, ...tail] = [1, 2, 3, 4];

You are saying assign the first element to head, and the remaining to tail. So, head = 1 and tail = [2,3,4].

In the answer that you cited, they are taking it one step further. They want the first (head), the second element (the head of the tail), and the remaining.

so what they want is [headTail, ...tailTail] = tail.

Now if we substitute the tail in the first statement, it becomes:

[head, ...[headTail, ...tailTail]] = [1,2,3,4]

where head = 1, headTail = 2 and tailTail = [3, 4]


You could simply do this instead:

[head, headTail, ...tailTail] = [1,2,3,4]

It will give the same outcome

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your complete and clear answer! I guess it was the second opening bracket that confused me all along.
0

This expression is "destructuring" a given array in the first element (head), the second element (headTail) and the rest (tailTail).

This simplier example should make it easier to understand:

let [head, ...tail] = [1, 2, 3, 4]; // head = 1, tail = [2, 3, 4]

This simple destructuring is just applied again to the tail in your example.

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.