BloG

Quick Tip: Find out how to Use the Spread Operator in JavaScript

Nov 22, 2022

On this tutorial, you’ll learn different ways you should use the spread operator in JavaScript, and the most important difference between the spread and rest operators.

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

The spread operator may 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 should be used right before the iterable object, with none separation. For instance:

console.log(arr);

Function Parameters

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

If you’ve got an array of numbers and you wish to find the minimum of those numbers, without the spread operator you’ll must either pass the weather one after the other using their indices or use the apply() method to pass the weather of the array as parameters. For instance:

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

Please note that the primary parameter is null, because the first parameter is used to vary the worth of this of the calling function.

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

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

You possibly can see it on this live example:

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

Create Arrays

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

For instance, it might probably be used to clone arrays. In case you simply assign a latest array the worth of an existing array, making changes to the brand new one will update the prevailing one:

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

Through the use of the spread operator, the exiting array may be cloned right into a latest array and any changes made into the brand new array wouldn’t affect the prevailing array:

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

It must be noted that this could only clone one-dimensional arrays. It might not work for multidimensional arrays.

The spread operator will also be used to concatinate a couple of array into one. For instance:

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

You may as well use the spread operator on a string to create an array where each item is a personality within the string:

const str = ‘Hello, World!’;
const strArr = [str];
console.log(strArr);

Create Objects

The spread operator may be utilized in other ways to create objects.

It could possibly be used to shallow-clone one other object. For instance:

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

It could possibly even be used to merge a couple of object into one. For instance:

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

It must be noted that, if the objects share the identical property names, the worth of the last object spread shall be used. For instance:

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

The spread operator may be used to create an object from an array, where the indices within the array turn out to be properties and the worth at that index becomes the worth of the property. For instance:

const numbers = [15, 13, 100, 20];
const obj = { numbers };
console.log(obj);

It could possibly even be used to create an object from a string, where, similarly, the indices within the string turn out to be properties and the character at that index becomes the worth of the property. For instance:

const str = ‘Hello, World!’;
const obj = { str };
console.log(obj);

Convert a NodeList to an Array

A NodeList is a set of nodes, that are elements within the document. The weather are accessed through methods within the collections, resembling item or entries, unlike arrays.

You need to use the spread operator to convert a NodeList to an Array. For instance:

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 set that stores unique values only. Much like the NodeList, a Set may be converted to an array using the spread operator.

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

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 remaining operator can be a three-dot operator (…), but it surely’s used for a unique purpose. The remaining operator may be utilized in a function’s parameter list to say that this function accepts an undefined variety of parameters. These parameters may be handled as an array.

For instance:

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

return sum;
}

In this instance, the remaining operator is used as a parameter of the calculateSum function. Then, you loop over the items within the array and add them as much as calculate their sum.

You possibly can then either pass variables one after the other to the calculateSum function as arguments, or use the spread operator to pass the weather of an array as arguments:

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

Conclusion

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

Related reading: