DEV Community

Discussion on: 5 Uses for the Spread Operator

Collapse
 
docx profile image
Lukáš Doležal • Edited

Great stuff. Note that spread operator works also in deconstruction too, not only construction:

Take first (or n first) fields of an array:

let [first, ...rest] = [1, 2, 3, 4, 5];
// first == 1
// rest == [2, 3, 4, 5]

Or as function definition:

function giveMeAllTheParams(...params) {
  console.log(`You gave me ${params.length} params`);
}

giveMeAllTheParams(1, 2, 3, 4, 5);
// You gave me 5 params
Collapse
 
laurieontech profile image
Laurie

All great examples!

Collapse
 
gregbacchus profile image
Greg Bacchus • Edited

Likewise for objects, can be used to create a new one that omits certain properties.

const {a, ...rest} = {a: 1, b: 2, c: 3};
Collapse
 
jwkicklighter profile image
Jordan Kicklighter

I always forget this since there seem to be more places to use the construction functionality. Thanks for the reminder!

Collapse
 
araw830 profile image
Atul Rawat

Good one😍