2

Is the ... operator the "spread" operator that has a two different semantics depending on its lexical position (parameter position vs destructuring assignment, Arrays, argument position etc)?

Or does it have two names "spread" and "rest"?

Ben Aston
  • 53,718
  • 65
  • 205
  • 331
  • 1
    It's both `spread` and `rest` depending on current position in code. – Egor Stambakio Jun 27 '17 at 17:35
  • So is it infact two operators with the same appearance or one operator with two names? – Ben Aston Jun 27 '17 at 17:35
  • 3
    See https://stackoverflow.com/q/37151966/710446 for a great explanation from Felix of "there is no such thing as the rest 'operator'" -- it's not an operator because an "operator" is a construct that takes operands and yields a result which can be fed into other operators. `...` does not meet this defintion – apsillers Jun 27 '17 at 17:38
  • 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 16 '21 at 12:11

2 Answers2

3

It's the same operator with different names based on the usage.

Rest Properties

Rest properties collect the remaining own enumerable property keys that are not already picked off by the destructuring pattern. Those keys and their values are copied onto a new object.

let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
x; // 1
y; // 2
z; // { a: 3, b: 4 }

Spread Properties

Spread properties in object initializers copies own enumerable properties from a provided object onto the newly created object.

let n = { x, y, ...z };
n; // { x: 1, y: 2, a: 3, b: 4 }

more ...

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • And of course "rest parameters"(?), "argument spreading" and "iterator spreading"(?). I am unsure of the naming! Have I missed anything? – Ben Aston Jun 27 '17 at 18:02
0

They are quite different as Spread Operator is unpacking collected elements such as arrays into single elements. But Rest Operator is collecting all remaining elements into an array or object. For example; Spread on array:

const arrOne = ['I', 'love', 'Programming']
const arrTwo = ['Programming', 'is', 'life']

const arrThree = [...arrOne, 'and', ...arrTwo]
console.log(arrThree);

Output is: [ 'I', 'love', 'Programming', 'Programming', 'is', 'life']

Rest on array: By destructuring array,

const [idx1, ...restArrValue] = arrOne;
console.log(idx1, restArrValue);

Output is: I [ 'love', 'Programming' ]

Again spread for unpacking

console.log(idx1, ...restArrValue);

Output is: I love Programming

I think this concept is clear as well.

mdmostafa
  • 618
  • 9
  • 19