The spread syntax allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) or multiple variables (for destructuring assignment) are expected.
Copying an object but replacing some properties:
This one we will need bable to make it work
const myClient = {
name : 'John',
lastname: 'Doe',
city: 'London'
}
function getNewClient(client, newName) {
return {
...client,
name: newName
}
}
const myClientB = getNewClient(myClient);
console.log(myClientB);
We can pass arguments to a function:
const numbers = [3, 5, 6] ;
function sumThreeNumbers(a, b, c) {
return a + b + c;
}
const result = sumThreeNumbers(...numbers)
console.log(result);
We can concat arrays
const numbersA = [1, 2, 3];
const numbersB = [4, 5, 6];
const totalNumbers = [...numbersA, ...numbersB, 7, 8]
console.log(totalNumbers);
Nice! Some common pitfalls off the top of my head:
Please be aware that last wins.
arrays spread operator throws if first one is undefined, only on TypeScript (see #15027).
spread operator is dangerous in React if you use PureComponent and pass in more properties than the component needs. It may render unnecessarily, when extra properties change, thus hurting performance.