Skip to content

Instantly share code, notes, and snippets.

@brauliodiez brauliodiez/
Last active Apr 15, 2018

What would you like to do?
Spread Operator simple samples

spread operator

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 {
    name: newName

const myClientB = getNewClient(myClient);

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)

We can concat arrays

const numbersA = [1, 2, 3];
const numbersB = [4, 5, 6];

const totalNumbers = [...numbersA, ...numbersB, 7, 8]


This comment has been minimized.

Copy link

pablonete commented Jun 21, 2017

Nice! Some common pitfalls off the top of my head:

  1. Somehow people prefer to add the object spread the last, which may introduce bugs, like if you were written:
  return {
    name: newName,

Please be aware that last wins.

  1. arrays spread operator throws if first one is undefined, only on TypeScript (see #15027).

  2. 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.