12

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.

Jeremy Swagger
  • 1,101
  • 1
  • 16
  • 18
Bill
  • 13,703
  • 14
  • 67
  • 112
  • Does this answer your question? [Spread Syntax vs Rest Parameter in ES2015 / ES6](https://stackoverflow.com/questions/33898512/spread-syntax-vs-rest-parameter-in-es2015-es6) – Henke Mar 15 '21 at 14:55

2 Answers2

24

...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.

ibrahim mahrir
  • 28,583
  • 5
  • 34
  • 61
Merott
  • 6,527
  • 6
  • 32
  • 50
  • so basically it's a concat? – Bill Nov 24 '15 at 10:06
  • 1
    It's not a `concat`, but in this case it has the same result. See [this answer](http://stackoverflow.com/questions/20541339/usage-of-rest-parameter-and-spread-operator-in-javascript). – Merott Nov 24 '15 at 10:09
  • 2
    It's not an operator (and cannot be an operator). it's just syntax. – T.J. Crowder Jan 26 '17 at 08:56
  • 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. – Merott Jan 26 '17 at 12:21
  • @Merott AFAIK, the spread syntax is **not an operator**. An operator by definition return/yield a value. For example the plus operator yields the sum of its operands: `var sum = (a + b);`, the unary minus returns the negative of its operand: `var neg = -a;`. Whereas the spread syntax doesn't, `var res = ...someArray;` will throw an error, and thus the spread syntax can't be called an operator, because it doesn't yield a value. Although they seem to have dubbed it operator on some sites. – ibrahim mahrir Mar 22 '18 at 16:49
  • 1
    @ibrahimmahrir OK, thanks. I'm updating my answer to call it *syntax*. Even Mozilla have updated their docs. – Merott Mar 23 '18 at 17:34
3

...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

Simon H
  • 17,952
  • 10
  • 57
  • 101