Spread Destructuring
The spread operator ...
can be used to destructure arrays, other iterables and objects. It is used to catch remaining properties not already picked off by the destructuring pattern.
const array = [1, 2, 3, 4];
const [first, ...theRest] = array;
console.log(first, theRest); // 1 [2,3,4]
const object = {a: 1, b: 2, c:3};
const {a, ...theRest} = object;
console.log(a, theRest); // 1 {b: 2, c: 3}
Spread Parameters
In addition to spread destructuring, the spread operator ...
can be used to unpack an array into its elements in order to be passed into a function as individual arguments.
function f (a,b,c) {
console.log(a,b,c);
};
var values = [1,2,3];
f(...values); // 1 2 3
Spread parameters can also be mixed and matched with normal function parameters.
function f (a,b,c,d) {
console.log(a,b,c,d);
};
var values = [2,3];
f(1,...values,4); // 1 2 3 4
Rest Spread Parameters
Rest spread parameters are used to capture all remaining parameters passed to a function and expose them as an array. No other named arguments may follow the rest parameters in the function signature.
function f (first,second,...numbers) {
console.log(first,second,numbers);
}
f(1,2,3,4,5); // 1 2 [3,4,5]
Spread Property Initialisers
Spread properties in object initializers copies the enumerable properties from a provided object onto the newly created object.
const foo = {a: 2, b: 3};
const bar = {a: 1, ...foo};
bar; // {a: 2, b: 3}
Happy Coding 😀
Top comments (0)