How do rest and spread syntax differ in JavaScript?
Quick answer
The same ... notation has two different jobs depending on where it appears. Rest collects remaining values into a single array or object binding; spread expands values into a place that accepts separate arguments, array elements, or object properties. For example, function f(...items) collects arguments, while [...items] expands an iterable into a new array. Read the surrounding syntax to tell which operation is happening. [S1] [S2] [S3]
The question, the details, the next step.
A practical checklist
A few more useful answers
Can I put a function rest parameter before another parameter?
No. A rest parameter must be last in the function’s parameter list. [S1]
Can I use an ordinary object with spread in an array literal?
Not unless it is iterable: array-literal and call spread use iterable items. Object-literal spread instead enumerates the source’s own properties. [S3]
Does `[...items]` make a deep copy?
No. Array and object copies made with spread are shallow; nested values are not recursively copied. [S3]
Sources
References used for this guide.
- [S1] Rest parameters - JavaScript | MDN developer.mozilla.org · Checked
- [S2] Destructuring - JavaScript | MDN developer.mozilla.org · Checked
- [S3] Spread syntax (...) - JavaScript | MDN developer.mozilla.org · Checked
