Quick Tip: How to Use the Spread Operator in JavaScript

Share this article

How to Use the Spread Operator in JavaScript

In this tutorial, you’ll learn the different ways you can use the spread operator in JavaScript, and the main difference between the spread and rest operators.

Symbolized by three dots (...), the JavaScript spread operator was introduced in ES6. It can be used to expand elements in collections and arrays into single, individual elements.

The spread operator can be used to create and clone arrays and objects, pass arrays as function parameters, remove duplicates from arrays, and more.

Syntax

The spread operator can only be used on iterable objects. It must be used right before the iterable object, without any separation. For example:

console.log(...arr);

Function Parameters

Take as an example the Math.min() method. This method accepts at least one number as a parameter and returns the smallest number among the passed parameters.

If you have an array of numbers and you want to find the minimum of these numbers, without the spread operator you’ll need to either pass the elements one by one using their indices or use the apply() method to pass the elements of the array as parameters. For example:

const numbers = [15, 13, 100, 20];
const minNumber = Math.min.apply(null, numbers);
console.log(minNumber); // 13

Please note that the first parameter is null, since the first parameter is used to change the value of this of the calling function.

The spread operator is a more convenient and readable solution to pass the elements of an array as parameters to the function. For example:

const numbers = [15, 13, 100, 20];
const minNumber = Math.min(...numbers);
console.log(numbers); // 13

You can see it in this live example:

See the Pen Use Spread Operator in Functions JS by SitePoint (@SitePoint) on CodePen.

Create Arrays

The spread operator can be used to create new arrays from existing arrays or other iterable objects that include the Symbol.iterator() method. These are objects that can be iterated using the for...of loop.

For example, it can be used to clone arrays. If you simply assign a new array the value of an existing array, making changes to the new one will update the existing one:

const numbers = [15, 13, 100, 20];
const clonedNumbers = numbers;
clonedNumbers.push(24);
console.log(clonedNumbers); // [15, 13, 100, 20, 24]
console.log(numbers); // [15, 13, 100, 20, 24]

By using the spread operator, the exiting array can be cloned into a new array and any changes made into the new array wouldn’t affect the existing array:

const numbers = [15, 13, 100, 20];
const clonedNumbers = [...numbers];
clonedNumbers.push(24);
console.log(clonedNumbers); // [15, 13, 100, 20, 24]
console.log(numbers); // [15, 13, 100, 20]

It should be noted that this would only clone one-dimensional arrays. It would not work for multidimensional arrays.

The spread operator can also be used to concatinate more than one array into one. For example:

const evenNumbers = [2, 4, 6, 8];
const oddNumbers = [1, 3, 5, 7];
const allNumbers = [...evenNumbers, ...oddNumbers];
console.log(...allNumbers); //[2, 4, 6, 8, 1, 3, 5, 7]

You can also use the spread operator on a string to create an array where each item is a character in the string:

const str = 'Hello, World!';
const strArr = [...str];
console.log(strArr); // ['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']

Create Objects

The spread operator can be used in different ways to create objects.

It can be used to shallow-clone another object. For example:

const obj = { name: 'Mark', age: 20};
const clonedObj = { ...obj };
console.log(clonedObj); // {name: 'Mark', age: 20}

It can also be used to merge more than one object into one. For example:

const obj1 = { name: 'Mark', age: 20};
const obj2 = { occupation: 'Student' };
const clonedObj = { ...obj1, ...obj2 };
console.log(clonedObj); // {name: 'Mark', age: 20, occupation: 'Student'}

It should be noted that, if the objects share the same property names, the value of the last object spread will be used. For example:

const obj1 = { name: 'Mark', age: 20};
const obj2 = { age: 30 };
const clonedObj = { ...obj1, ...obj2 };
console.log(clonedObj); // {name: 'Mark', age: 30}

The spread operator can be used to create an object from an array, where the indices in the array become properties and the value at that index becomes the value of the property. For example:

const numbers = [15, 13, 100, 20];
const obj = { ...numbers };
console.log(obj); // {0: 15, 1: 13, 2: 100, 3: 20}

It can also be used to create an object from a string, where, similarly, the indices in the string become properties and the character at that index becomes the value of the property. For example:

const str = 'Hello, World!';
const obj = { ...str };
console.log(obj); // {0: 'H', 1: 'e', 2: 'l', 3: 'l', 4: 'o', 5: ',', 6: ' ', 7: 'W', 8: 'o', 9: 'r', 10: 'l', 11: 'd', 12: '!'}

Convert a NodeList to an Array

A NodeList is a collection of nodes, which are elements in the document. The elements are accessed through methods in the collections, such as item or entries, unlike arrays.

You can use the spread operator to convert a NodeList to an Array. For example:

const nodeList = document.querySelectorAll('div');
console.log(nodeList.item(0)); // <div>...</div>
const nodeArray = [...nodeList];
console.log(nodeList[0]); // <div>...</div>

Remove Duplicates from Arrays

A Set object is a collection that stores unique values only. Similar to the NodeList, a Set can be converted to an array using the spread operator.

Since a Set only stores unique values, it can be paired with the spread operator to remove duplicates from an array. For example:

const duplicatesArr = [1, 2, 3, 2, 1, 3];
const uniqueArr = [...new Set(duplicatesArr)];
console.log(duplicatesArr); // [1, 2, 3, 2, 1, 3]
console.log(uniqueArr); // [1, 2, 3]

Spread Operator vs Rest Operator

The rest operator is also a three-dot operator (...), but it’s used for a different purpose. The rest operator can be used in a function’s parameter list to say that this function accepts an undefined number of parameters. These parameters can be handled as an array.

For example:

function calculateSum(...funcArgs) {
  let sum = 0;
  for (const arg of funcArgs) {
    sum += arg;
  }

  return sum;
}

In this example, the rest operator is used as a parameter of the calculateSum function. Then, you loop over the items in the array and add them up to calculate their sum.

You can then either pass variables one by one to the calculateSum function as arguments, or use the spread operator to pass the elements of an array as arguments:

console.log(calculateSum(1, 2, 3)); // 6
const numbers = [1, 2, 3];
console.log(calculateSum(...numbers)); // 6

Conclusion

The spread operator allows you to do more with fewer lines of code, while maintaining the code readability. It can be used on iterable objects to pass parameters to a function, or to create arrays and objects from other iterable objects.

Related reading:

Frequently Asked Questions (FAQs) about JavaScript Spread Operator

What is the difference between the spread operator and the rest parameter in JavaScript?

The spread operator and the rest parameter in JavaScript both use the same syntax of three dots (…). However, they serve different purposes. The spread operator is used to split up array elements or object properties. It allows an iterable such as an array expression or string to be expanded in places where zero or more arguments or elements are expected. On the other hand, the rest parameter is used to combine a variable number of arguments into an array. When defining a function, you can use the rest parameter to allow it to accept any number of arguments.

Can I use the spread operator with objects in JavaScript?

Yes, the spread operator can be used with objects in JavaScript. It is used to make shallow copies of JS objects. Using the spread syntax, you can create a new object with new properties, and also inherit properties from another object. This is particularly useful when you want to merge two or more objects, or modify some properties of an existing object while keeping the rest intact.

How does the spread operator work with arrays in JavaScript?

The spread operator can be used to expand elements of an array in places where zero or more arguments or elements are expected. For example, it can be used in function calls, array literals, and other similar constructs. It essentially takes an array and spreads it out into individual elements. This can be particularly useful when you want to concatenate arrays, or when you want to pass an array to a function that expects individual arguments.

Can the spread operator be used to clone an array or object?

Yes, the spread operator can be used to clone an array or object. When used with an array, it creates a new array with the same elements. When used with an object, it creates a new object with the same properties. However, it’s important to note that this is a shallow copy, which means that it only copies the top-level elements or properties. If the array or object contains other arrays or objects, those are copied by reference, not by value.

What is the performance of the spread operator compared to other methods?

The performance of the spread operator can vary depending on the JavaScript engine and the specific use case. In general, it tends to be slower than traditional methods like for loops or the Array.prototype.concat method for concatenating arrays. However, the difference in performance is usually negligible unless you’re dealing with very large arrays or performance-critical code. The spread operator offers more readability and ease of use, which can often outweigh the slight performance cost.

Is the spread operator supported in all browsers?

The spread operator is a relatively new addition to JavaScript, introduced in ES6 (ECMAScript 2015). It is supported in all modern browsers, including Chrome, Firefox, Safari, and Edge. However, it is not supported in Internet Explorer. If you need to support older browsers, you may need to use a transpiler like Babel to convert your code into ES5 syntax.

Can I use the spread operator in a function call?

Yes, the spread operator can be used in a function call. When used in this way, it spreads an array into individual arguments to the function. This can be particularly useful when you have an array of values that you want to pass to a function as separate arguments.

How does the spread operator handle nested arrays or objects?

The spread operator only performs a shallow copy, which means it only copies the top-level elements or properties. If an array or object contains other arrays or objects, those are copied by reference, not by value. This means that if you modify the nested arrays or objects, those changes will be reflected in the original array or object.

Can I use the spread operator with strings in JavaScript?

Yes, the spread operator can be used with strings in JavaScript. When used with a string, it splits the string into an array of individual characters. This can be useful when you want to create an array from a string, or when you want to spread a string into individual characters in a function call or array literal.

Can the spread operator be used with sets and maps in JavaScript?

Yes, the spread operator can be used with sets and maps in JavaScript. When used with a set, it creates a new array with the elements of the set. When used with a map, it creates a new array with the key-value pairs of the map. This can be useful when you want to convert a set or map into an array, or when you want to spread a set or map into individual elements in a function call or array literal.

Dianne PenaDianne Pena
View Author

Dianne is SitePoint's newsletter editor. She especiallly loves learning about JavaScript, CSS and frontend technologies.

JS Quick Tipsspread operator
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week