logo

The Spread Operator

June 7, 2021

Spread syntax allows an iterable such as an array, an object or a string to be expanded by using `...`.

Let's try a couple of examples:

Given an array const arr1 = [1, 2, 3], you can create a new array using the spread operator.

const arr2 = [...arr1, "x", "y", "z"];
console.log(arr2);
// expected output: [1, 2, 3, "x", "y", "z"]

You can create a copy of an existing array, without mutating it:

const currentArray = ["a", "b", "c"];
const newArray = [...currentArray];
console.log(newArray);
// expected output: ["a", "b", "c"]

You can also use the spread operator inside an object literal in order to add the properties of oldObj to the newObj:

const oldObj = { id: 10, username: "Joly" };
const newObj = { ...oldObj };
console.log(newObj);
// expected output: {id: 10, username: "Joly"}

You can also update non-destructively a property:

const obj = { id: 17, username: "likhbmkhd", name: "Joy" };
const updatedObj = { ...obj, name: "Joye" };
console.log(updatedObj);
// expected output: {id: 17, username: "likhbmkhd", name: "Joye"}

The spread operator also works with strings, which will create an array that contains each character from the string.

const str = "Hello";
const arrStr = [...str];
console.log(arrStr);
// expected output: ["H", "e", "l", "l", "o"]

You can also spread the argument of a function call, with the condition that the argument must be an iterable object.

function calculateSum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

console.log(calculateSum(...numbers));
// expected output: 6

Note: all values are spreadable

You can also spread undefined, null, numbers or strings:

{...undefined} // {}
{...null} // {}
{...10}; // {}
{...'abcd'}; // {0: "a", 1: "b", 2: "c", 3: "d"}
{...['a', 'b']}; // {0: "a", 1: "b"}

Use cases

  • Merging arrays - we can merge two arrays:
const arr1 = [1, 2];
const arr2 = [3, 4];

const mergedArray = [...arr1, ...arr2];
console.log(mergedArray);
// expected output: [1, 2, 3, 4]
  • Find the largest number inside an array
const arr1 = [1, 5, 9, 3];

const largestNumber = Math.max(...arr1);
console.log(largestNumber);
// expected output: 9
  • Copying objects - we can reate a copy of an object
const original = { a: 1, b: 2 };
const copy = { ...original };
console.log(copy);
// expected output: {a: 1, b: 2}