According to Mozilla developer website spread operator (…) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

What a huge sentence, isn’t it? This definition definitely sounded complex the first time I read it. There are many different use cases of the spread operator and that’s what I will be summarizing in this blog post today. Hopefully I don’t get confused next time I need to catch up on this. I hope this will help others as well!

Let’s break it down into following categories and subcategories:

  • spread operator in arrays
    • function calls
    • array literals
  • spread operator in objects
  • spread operator and strings

spread operator in arrays

Function calls

1. Spreading out an array into a function’s arguments

Let’s say you need to call a function test that accepts multiple arguments. Instead of  invoking the function test like this test(1, 2, 3), you can pass in an array with the spread syntax test(...[1, 2, 3]) and the spread operator will “spread”out this array into different arguments. So any function that accepts multiple number of arguments can benefit from the use of spread operator.

Think of this simple example of a sum function that is defined with three arguments and is invoked with an array using the spread syntax (...[1, 2, 3]) instead of three separate arguments.

 

const sum = (num1, num2, num3) => num1 + num2 + num3;

console.log(sum(...[1, 2, 3]));

Don’t get confused with the rest syntax which looks exactly like spread syntax. In a way, rest syntax is the opposite of spread syntax. Spread syntax “expands” an array into its elements, while rest syntax collects multiple elements and “condenses” them into a single element. See rest parameters.

2. Calling Functions without Apply

With the apply method we can use the elements of an array as arguments to a function.

 

const sum = (num1, num2, num3) => num1 + num2 + num3;

console.log(sum.apply(null, [1, 2, 3]));

The spread operator replaces the apply method all together. Our code is shorter, simpler and there is no need to use null!!

const sum = (num1, num2, num3) => num1 + num2 + num3;

console.log(sum(...[1, 2, 3]));

 

3. Using Math functions

The Math object’s set of functions are a perfect example of  being used with the spread operator. Without the spread operator we had to use Math.max.apply(null,[1, 2, 3]).

Math.max([1, 2, 3]) returns NaN, since Math.max() expects comma-separated arguments and not an array. The spread operator “spreads” out an array into different arguments and makes our code better to read and maintain.

 

const arr = [5, 12, 4, 21];
const maximum = Math.max(...arr);
const minimum = Math.min(...arr);

4 Using push and unshift to add elements to an array

If you would like to add elements of an array to the beginning of another array, you could use the unshift method and pass an array using the apply method as follows:

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
Array.prototype.unshift.apply(arr1, arr2)
console.log(arr1); [4, 5, 6, 1, 2, 3]

This code looks quite verbose. The spread operator definitely improves the readability of the code:

arr1.unshift(...arr2)

If you would like to add elements of an array to the end of another array, this can be accomplished with push method as follows:

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
arr1.push(...arr2); 
console.log(arr1) // [1, 2, 3, 4, 5, 6]
Array literals

1. copy arrays

Copy all contents of arr1 into another array arr2 using the spread operator.

let arr1 = [1, 2, 3]
let arr2 = [...arr1];
console.log(arr2) // [1, 2, 3]

Note: Spread syntax effectively goes one level deep while copying an array. Therefore, it may be unsuitable for copying multidimensional arrays

2. merge arrays

Concatenating arrays with the spread operator is very simple.

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];

let combined = [...arr1, ...arr2];

console.log(combined) // [1, 2, 3, 4, 5, 6]

You can concatenate more than two arrays if you wish [...arr1, ...arr2, ...arr3]

3. add elements of an array to another array

If you’d like to combine two arrays and place elements at any place within the array, you can do as follows:

let arr1 = [2, 3];
let arr2 = [1, ...arr1, 4, 5];
console.log(arr2);

spread operator in objects

1. clone an object

It is very easy to clone an object using the spread operator.

let obj1 = { food: 'pizza', drink: 'Coca cola' };

let clonedObj = { ...obj1 };
// Object { food: 'pizza', drink: 'Coca cola' }

 

2. merge two objects

The spread operator offers a simple way of merging two objects.

let profile = { name: 'Panagiota', age: 36 };
let other = { 'hobbies': ['Cooking', 'Studying']};
let summary = {...profile, ...other};
console.log(summary)

 

3. destructure an object

You can use destructuring and the rest operator together to extract the information into variables as you’d like them:

const {firstname, ...rest } = { firstname: 'Panagiota', age: 36, profession: 'Software Engineer' };
console.log(firstname, rest);

 

spread operator and strings

  1. convert a string into an array

There are many ways to convert a string into an array of characters. 'Hello'.split('')is a common way to do so. Here’s how you can do it with the use of spread operator.

let name = "Panagiota";
let characters = [...name];
console.log(characters);