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"?
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"?
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 }
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.