Skip to content
Advertisement

rest / spread in java script

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!

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement