Spread Operator

Understanding ES6 spread operator

The ES6 spread operator allows an array or an object to be spread or flattened into its elements; this is syntactically similar to the way arrays are implemented in languages like Python and R.

  • Spread operator: loops through an array, pushing each item from the current array into a new one.

  • Spread is mainly used with arrays, but it can also be applied to objects.

  • It breaks it up into individual variables of the same name, or — merges a list of variables into a single statement, or — converts an object to an array.

Spread is mainly used for unpacking arrays into their members, but can also be useful when dealing with nested object structures where certain values are shared between them (e.g., key-value pairs). It is not possible to apply the spread operator to regular JavaScript functions, because that would result in undefined behavior. For example, let’s say you have a function that calculates the sum of three numbers:

const sumThree = (a, b, c) => a+b+c;

merging two or more arrays using spread operator:

let firstArray = [4, 5];
let secondArray = [9, 10];

let mergedArray = [...firstArray, ...secondArray];

//[4, 5, 9, 10]

You can also use this merging technique on objects:

let firstObject = { name: "Jack" };
let secondObject = { age: 19 };

let mergedObject = {...firstObject, ...secondObject};
// mergedObject is { name: "Jack", age: 19 }

But the spread operator can’t be used to pass object properties into a function:

let user = {
  name: "Jack",
  age: 27
};

const greetings = (name, age) => {
  console.log(`Hello, my name is ${name} and I'm ${age} years old`);
}

greetings(...user);
// Will cause an error
// Uncaught TypeError: Found non-callable @@iterator at <anonymous>:1:1

That will be it on Spread Operator