Skip to content

Instantly share code, notes, and snippets.

@brauliodiez
Last active April 15, 2018 07:02
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brauliodiez/7faa3dc1079f6890347423f8d951813a to your computer and use it in GitHub Desktop.
Save brauliodiez/7faa3dc1079f6890347423f8d951813a to your computer and use it in GitHub Desktop.
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.

steps

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);
@pablonete
Copy link

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,
    ...client,
  }

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