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.
...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.
so basically it's a concat?
It's not a
concat
, but in this case it has the same result. See this answer.It's not an operator (and cannot be an operator). it's just syntax.
I think the terms "syntax" and "operator" could be used interchangeably in this instance, at least for as long as the syntax is considered to be syntactic sugar abstracting or hiding away some complicated logic in plain JavaScript. However, if we're referring to the JavaScript engine's native capability to spread an array into its individual elements, I prefer to call it an "operator", because it would no longer be just a syntactical difference, i.e. there could be internal implementation differences with potential performance benefits.
@ibrahimmahrir OK, thanks. I'm updating my answer to call it syntax. Even Mozilla have updated their docs.