Spread and Rest Operators

The spread and rest operators us the same syntax ... (three dots). It’s usage determines whether you’re using it as the spread or rest operator.

Spread operator

The spread operator allows you to pull elements out of an array (split the array into a list of elements) or pull the properties out of an object.

Syntax

cost newArray = [...oldArray, 4, 5];
const newObj = { ...OldObject, newProp: 5 };

In the below example, the oldArray and the new items is added to the newArray.

const oldArray = [1, 2, 3];
const newArray = [...oldArray, 4, 5];
console.log(newArray); // This now is [1, 2, 3, 4, 5];

Spread operator used on an object

const objectOne = {
  name: 'bino'
};

const objectTwo = { 
  ...objectOne, 
  name2: 'Jino'
};

console.log(objectTwo);  // {name: 'bino', name2: 'Jino'}

The spread operator is extremely useful for cloning arrays and objects. Since both are reference types (and not primitives), copying them safely (i.e. preventing future mutation of the copied original) can be tricky. With the spread operator you have an easy way of creating a (shallow!) clone of the object or array.

Rest operator

The rest operator can used to merge a list of function arguments into an array.

function sortExa( ...args){
  return sort.args()
}

const filter = (...args) => {
  return args.filter(el => el === 1);
}

console.log(filter(1,2,3));

Read More