Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript es6 array feature [...data, 0] "spread operator"

I came across this in some example code and I am completely lost.

const addCounter = (list) => {
    return [...list, 0];  // This is the bit I am lost on, and I don't know about [...list, 0]
}

Apparently the above is equal to the following:

const addCounter = (list) => {
    return list.concat([0]);
}

Any suggestion or explaination is much appreciated.

like image 537
Bill Avatar asked Nov 24 '15 09:11

Bill


2 Answers

...list is using the spread syntax to spread the elements of list. Let's assume the list is [1, 2, 3]. Therefore [...list, 0] becomes:

[1, 2, 3, 0]

Which has the same result as doing list.concat([0]);

This is not a feature of the array in ES6, it's just been used for array concatenation. It has other uses. Read more on MDN, or see this question.

like image 109
Merott Avatar answered Sep 19 '22 12:09

Merott


...list spreads (lays) out all the elements in the array list.

so [...list, 0] is all of the elements of list with a 0 at the end

like image 43
Simon H Avatar answered Sep 18 '22 12:09

Simon H