Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 30, 2020 03:37 pm GMT

ES6 - Spread Operator

Introduction

In this article, let us look at a very powerful yet simple feature introduced with ES6 or ES2015 version of JavaScript, the Spread Operator.

Spread Operator

The spread operator expands an iterable object into its individual element. An iterable object is anything that you can loop over such as Array, Map, Set, DOM NodeList, etc.

A quick and easy example of spread operator is shown below:

//An Array of fruitsconst fruits = ['Apple', 'Banana', 'Watermelon'];//Output the value of array using spread operatorconsole.log(...fruits);//Output -> Apple Banana Watermelon

The spread syntax is denoted by three periods before the object. In the above example, the spread operator is used with the 'fruits' array and the values of array are printed in a single line using the console.log statement.

Use-Cases of Spread Operator

Copy Arrays

I think this is one of the most practical examples that you'll come across while programming using ES6 syntax.

The important thing to note from the below code example is that a shallow copy of the elements of the array 'animals' array is made while assigning to the array 'animalsCopy. This means they do not hold the same reference, which you can verify using the 'triple equals check' operator.

//animals array initializedconst animals = ['dog', 'sheep', 'goat'];//animalsCopy array is created with a Shallow copy of animals array valuesconst animalsCopy = [...animals];//Display value on the consoleconsole.log(animalsCopy);//Output -> Array(3)["dog", "sheep", "goat"]console.log(animals === animalsCopy); //Output -> false//Important thing to Note here is that animals !== animalsCopy (Only a Shallow copy is made)

Copy Objects

This is exactly same as copying arrays, except that we are using objects.

//Person objectconst person = { name : 'Skay',   age : 38 }//Shallow copy Person object using spread operator to create personCopy objectconst personCopy = {...person};console.log(personCopy); //Output -> { name: "Skay", age: 38 }console.log(person === personCopy); //Output -> false (Shallow copy)

Merging Arrays

The Spread operator provides a simple and effective way to merge arrays without the need to loop through them.

const maleActors = ['Brad Pitt', 'Chris Evans', 'Matt Damon'];const femaleActors = ['Jennifer Aniston', 'Jennifer Lawrence', 'Emma Stone']; const movieActors = [...maleActors, ...femaleActors];console.log(movieActors); //Output -> Array(6) [ "Brad Pitt", "Chris Evans", "Matt Damon", "Jennifer Aniston", "Jennifer Lawrence", "Emma Stone" ]

Merging Objects

Merging Objects is similar to merging arrays except that there's a 'key' or an 'attribute' in picture.

There are 2 possibilities when the two objects are merged:

  • key is unique - The key/value will be copied over to the new object.
  • key is common in both the objects - The value of the last object will replace the value of the previous object during merge.

The code example below will help in understand the scenario in a better way.

//Person1 Object containing the attributes name & ageconst person1 = {   name : "Skay",   age : 32 };//Person2 Object containing the attributes name, age & occupationconst person2 = {     name : "Skay",     age: 38,    occupation: "Web Developer" };//Both objects are merged using the spread operator//If key is not common between person1 & person2, then it's copied to the newPerson object//However, for the age attribute, the value of 'person2' will be replaced with the value of 'person1'const newPerson = {...person1, ...person2};console.log(newPerson) ; // Output -> {name: "Skay", age: 38, occupation: "Web Developer"}

Spread Operator - With Strings

The spread operator also works with strings. One practical example is extracting characters from a string.

//'name' variableconst name = 'Skay';//Spread Operator extracts the characters from the String and assigns to an arrayconst chars = [...name];console.log(chars); //Output -> Array (4)["S", "k", "a", "y"]

Spread Operator - Argument to a Function

This is another great practical example of passing an array into an argument of a function. Though, code readability becomes a topic of discussion when seeing spread operators as parameters to functions.

In the code example below, the spread operator spreads the variables into the argument in the same order they appeared in in the array. So 1 is passed into a, 2 is passed into b, and 3 is passed into c.

//Array of numbersconst arr = [1,2,3];//Arrow Function to add numbersconst add = (a,b,c) => a+b+c;//Passing the array as a spread operator to the function 'add'//The values of the array are spread across the variables in the same order //they appeared in the arrayconsole.log(add(...arr)); //Output -> 6

Spread Operator with Destructuring

Another common use-case which you will come across in several places is combining spread operator while destructuring.

Destructuring is another powerful feature introduced with ES6. You can read more about it over here.

In the code example below, the attributes 'occupation', 'skills' are by default assigned to the 'others' variable when the spread operator is used.

//Person Objectconst person = {    name : 'Skay',  age: 38,  occupation: 'Web Developer',    skills: 'HTML, CSS, JavaScript'};//Destructuring the Person object and assiging the values to name & age//The attributes occupation & skills are automatically assigned to 'others'//By using the spread operatorconst { name, age, ...others } = person;console.log(`Name is ${name}`); //Output -> Name is Skayconsole.log(`Age is ${age}`); //Output -> Age is 38console.log(others); // Output -> {occupation: "Web Developer", skills: "HTML, CSS, JavaScript"}

Convert NodeList to Array

This is another common example where you can use a spread operator. Typically, if we need to do any DOM manipulation of lists in a page, we will choose the elements from the DOM using a 'querySelectorAll' command.

When the 'querySelectorAll' command is used, it returns a NodeList. NodeList is similar to an array, but do not have the high-order methods of an array such as forEach, map, fitler, etc.

However, with spread operator, we can convert a NodeList into an Array in a single line.

/* Note: This is a sample code & will run with HTML code*///Assuming there's a number of list items with the className of 'items'//It will return a NodeList let nodeList = document.querySelectorAll('.items');//Using the spread operator, the nodeList is converted to an array//This gives us flexibility to use high-order array methods such as map, filter, etc.var nodeArray = [...nodeList]

Conclusion

As we can see, the spread syntax is a great convenience feature of JavaScript. We have seen the following features of spread operator in this article:

  • Combines 2 arrays into one.
  • Pass arrays into a function as arguments with a single line of code. Very useful, when there are a larger number of arguments exist for a function.
  • Can be combined with destructuring to extract specific values and assign the rest of values to a single variable.
  • Shallow copying of arrays & objects is possible.
  • Practical use-cases such as extracting characters from a string or converting a NodeList into an array can be achieved in a single line.

I hope you enjoyed this article. Thank you for taking the time to read it & do let me know your feedback on this article.

You might also like the following articles:


Original Link: https://dev.to/skaytech/es6-spread-operator-3ced

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To