Quick Tip: How to Use the Spread Operator in JavaScript

In this tutorial, you will learn about different ways to use spread operator in JavaScript and the main difference between 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 should be used immediately before iterable object without any separation. For example:

console.log(...arr);

function parameters

Take the Math.min() method, for example. This method accepts at least one number as a parameter and returns the smallest number of 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 will either have to pass the elements one by one using their indices or use Applicable() Method passing the elements of an 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 nullbecause the first parameter is used to change the value of this of calling function.

The spread operator is a more convenient and readable solution to passing elements of an array as parameters to a 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 pen
use spread operator in function js
by sitepoint (@SitePoint,
Feather codepen,

create array

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

For example, it can be used to clone arrays. If you just assign the value of an existing array to a new array, then 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); 

Using the spread operator, the exiting array can be cloned into a new array and any changes made to the new array will not 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 will only clone one dimensional arrays. This will not work for multidimensional arrays.

The spread operator can also be used to combine multiple arrays 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 a variety of ways to create objects.

This can be used to shallow-clone any other object. For example:

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

It can also be used to combine multiple objects 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 objects share the same property name, 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 indices into the array become properties and the value at that index becomes the property’s value. 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, similarly, the index in the string becomes the property and the character at that index becomes the property’s value. For example:

const str = 'Hello, World!';
const obj =  ...str ;
console.log(obj); 

convert nodelist to array

a nodelist is a collection of nodes, which are elements in the document. Elements in a collection are accessed through methods, such as item either entriesUnlike 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 array

a group Object is a collection that stores only unique values. Similar to NodeList, a set can be converted to an array using the spread operator.

Since a set only stores unique values, it can be combined 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 is 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. calculateSum Celebration. Then, you loop over the items in the array and add them to find their sum.

You can then either pass the variables one by one 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 readability of the code. It can be used to pass parameters to a function on iterable objects, or to create arrays and objects from other iterable objects.

Related Reading:

Leave a Reply