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
Table of Contents
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);
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);
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); console.log(numbers);
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); console.log(numbers);
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);
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);
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);
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);
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);
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);
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);
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)); const nodeArray = [...nodeList];
console.log(nodeList[0]);
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); console.log(uniqueArr);
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)); const numbers = [1, 2, 3];
console.log(calculateSum(...numbers));
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: