# ES6 Spread and Rest operator
Published on 14 April 2020

Spread operator example:

In an array:

const numbers = [1, 2 ,3 4];
const myNewArray = [...numbers, 5 , 6, 7];

console.log(myNewArray); //prints [1, 2, 3, 4, 5, 6, 7]

 

In a JSON object

const person = {
  name: 'Gokhan'
}

const otherPerson = {
  ...person,
  age: 31
}
console.log(otherPerson);//prints {name: 'Gokhan', age: 31}

 

Rest operator

(similar to Java varargs:

const glueNames = (...names) =>  names.map((elem, i) => {
  return {
    index: i,
    name: elem,
    nameCharacterCount: elem.length
  }
});

const out = glueNames("Gokhan", "Orhun", "Awesomeguy");
console.log(JSON.stringify(out));
//Will print the following array:
[
  {
    "index": 0,
    "name": "Gokhan",
    "nameCharacterCount": 6
  },
  {
    "index": 1,
    "name": "Orhun",
    "nameCharacterCount": 5
  },
  {
    "index": 2,
    "name": "Awesomeguy",
    "nameCharacterCount": 10
  }
]