Learn JavaScript Spread Operator - with 15 Examples


The spread operator is a wonderful feature of JavaScript which was introduced in ES6. It allows us to expand an iterable object (such as an array, string, or object) into multiple elements.

The Spread operator is denoted by three dots (...) and is used to expand an iterable object into multiple elements.

It has vast applications in JavaScript. It can be used to copy an array, concatenate arrays, pass an array as an argument to a function, and many more.

For example, if we have an array arr = [1, 2, 3], we can expand it into multiple elements using the spread operator as console.log(...arr). This will print 1 2 3 in the console.

Example

let arr = [1, 2, 3];
// expand the array into multiple elements
console.log(...arr); // 1 2 3

let str = "abc";
// expand the string into multiple characters
console.log(...str); // a b c

In the above example, you have seen how you can expand an array of a string (or any iterable) into multiple elements.

Let's now look at multiple applications of the spread operator with examples.


1. Creating a Copy of an Array

One of the most common applications of the spread operator is to create a copy of an array.

For example, if we have an array arr = [1, 2, 3], we can create a copy of it using the spread operator as let arrCopy = [...arr].

Example

let arr = [1, 2, 3];
let arrCopy = [...arr];
console.log(arrCopy); // [1, 2, 3]

2. Combining Arrays

Another common application of the spread operator is to combine two or more arrays.

You can concatenate two or more arrays using the spread operator as let arr = [...arr1, ...arr2, ...arr3].

Example

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let arr3 = [7, 8, 9];

// combine the arrays
let arr = [...arr1, ...arr2, ...arr3];
console.log(arr);
// [1, 2, 3, 4, 5, 6, 7, 8, 9]

3. Adding Elements to an Array

The Spread operator can also be used to add elements to an array.

For this purpose, you need to work in steps:

  1. First, cut the array at the index where you want to add the new element. Example: arr.slice(0, 2)
  2. Then, also cut the array from the index where you want to add the new element. Example: arr.slice(2)
  3. Then, combine the two arrays using the spread operator. Example: let arr = [...arr.slice(0, 2), 4, ...arr.slice(2)]

Here is an example:

Example

let arr = [1, 2, 3, 5, 6, 7];

// add 4 at index 3
arr = [...arr.slice(0, 3), 4, ...arr.slice(3)];
console.log(arr);
// [1, 2, 3, 4, 5, 6, 7]

4. Removing Elements from an Array

Just like adding elements to an array, you can also use the spread operator to remove elements from an array.

Just like the above step you can use the slice() method to cut the array at the index where you want to remove the element. Then, combine the two arrays using the spread operator.

Example

let arr = [1, 2, 3, 4, 5];

// remove element at index 3
arr = [...arr.slice(0, 2), ...arr.slice(3)];
console.log(arr);
// [1, 2, 4, 5]

5. Passing an Array as an Argument to a Function

One of the most useful applications of the spread operator is that it can pass all the elements of an array as individual arguments to a function.

For example, if we have a function sum() that takes as many arguments as you want, you can pass an array of numbers to it as sum(...arr).

Example

function sum(...args) {
  let sum = 0;
  for (let i = 0; i < args.length; i++) {
    sum += args[i];
  }
  return sum;
}

let arr = [1, 2, 3, 4, 5];
console.log(sum(...arr)); // 15

6. Using Spread Operator with Math.max()

The Spread operator can be used with Math.max() function to find the maximum value in an array.

For example, if you have an array of numbers, you can find the maximum value using Math.max() as Math.max(...arr).

Example

let arr = [5, 1, 22, 45, 8, 10];

let max = Math.max(...arr);
console.log(max); // 45

7. Using Spread Operator with Math.min()

Just like we calculate the maximum value of an array above using Math.max(), in the same way spread operator can be used with Math.min() function to find the minimum value in an array.

Example

let arr = [5, 1, 22, 45, 8, 10];

let min = Math.min(...arr);
console.log(min); // 1

8. Create Copy of Object

Just like the array spread operator can also be used to create a copy of an object.

For example, if you have an object obj, you can create a copy of it using let copy = {...obj}.

Example

let obj = {
  name: 'Alex',
  age: 25
};

let copy = {...obj};
console.log(copy);
// {name: "Alex", age: 25}

9. Merge Two Objects

You can also combine the properties of two objects using the spread operator.

For example, if you have two objects obj1 and obj2, you can combine them using let obj = {...obj1, ...obj2}.

Example

let obj1 = {
  name: 'Alex',
  age: 25
};

let obj2 = {
  city: 'New York',
  country: 'USA'
};

let obj = {...obj1, ...obj2};
console.log(obj);
// {name: "Alex", age: 25, city: "New York", country: "USA"}

10. Get All Characters of a String

Just like separating an array into individual elements, you can also separate a string into individual characters using the spread operator.

For example, if you have a string str, you can separate it into individual characters using let chars = [...str].

Example

let str = 'To DO';
let chars = [...str];
console.log(chars);
// ["T", "o", " ", "D", "O"]

11. Convert Set to Array

Set is a data structure that does not allow duplicate values. You can't access elements of a set using the index. But you can convert a set to an array using the spread operator.

For example, if you have a set, you can convert it to an array using let arr = [...set].

Example

let set = new Set();
set.add('apple');
set.add('banana');
set.add('orange');

// Convert set to array
let arr = [...set];
console.log(arr);
console.log(Array.isArray(arr));

12. Convert Map to Array

Map is a data structure that stores key-value pairs. You can't access elements of a map using the index. But you can convert a map to an array using the spread operator.

For example, if you have a map, you can convert it to an array using let arr = [...map].

Example

let map = new Map();
map.set('fruit', 'apple');
map.set('vegetable', 'carrot');

// Convert map to array
let arr = [...map];
console.log(arr);
console.log(Array.isArray(arr));

13. Convert Array to Set

Just like converting a set to an array, you can also convert an array to a set using the spread operator.

Instead of manually adding each element of an array to a set, one by one, the spread operator provides a much more efficient and convenient way to convert an array to a set.

By spreading the array into a new Set constructor, as in the example let set = new Set([...arr]), you can quickly and easily convert an entire array to a set.

Example

let arr = ['apple', 'banana', 'orange'];

// Convert array to set
let set = new Set([...arr]);

set.forEach((value) => {
  console.log(value);
});

14. Convert Array to Map

Another use of the spread operator is to convert an array to a map.

Instead of iterating through the array and adding each element to a map individually, you can use the spread operator to quickly convert the entire array to a map.

By spreading the array into a new Map constructor, as in the example let map = new Map([...arr]).

Example

let arr = [["fruit", "apple"], ["vegetable", "carrot"]];

// Convert array to map
let map = new Map([...arr]);

map.forEach((value, key) => {
  console.log(key, value);
});

15. Clone Multiple Nodes at Once

One unique use of the javascript spread operator with DOM elements is to clone multiple elements at once.

Instead of using the cloneNode() method on each element individually, you can use the spread operator to clone multiple elements at once by spreading them into a new NodeList.

Example

let nodes = document.querySelectorAll('.node');
let clonedNodes = [...nodes].map(node => node.cloneNode(true));

The above code will clone all the elements with the class node and store them in the clonedNodes variable.

It's a more efficient way of cloning multiple elements as it eliminates the need to loop through each element and clone them individually.


Conclusion

The spread operator is a very useful operator that can be used in many different ways. It can be used at lots of places where you would otherwise have to use a for loop.

It is a very powerful operator that can be used to make your code more concise and efficient.

Hopefully, this article has helped you understand the spread operator in JavaScript.

Happy coding!😇