spread.jpeg

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 elements. An iterable object is anything that you can loop over such as Array, Map, Set, DOM NodeList, etc.

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

//An Array of fruits
const fruits = ['Apple', 'Banana', 'Watermelon'];

//Output the value of the array using the spread operator
console.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 the 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 initialized
const animals = ['dog', 'sheep', 'goat'];

//animalsCopy array is created with a Shallow copy of animals array values
const animalsCopy = [...animals];

//Display value on the console
console.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 the same as copying arrays, except that we are using objects.

//Person object
const person = 
{ name : 'Skay', 
  age : 38 
}

//Shallow copy Person object using spread operator to create personCopy object
const 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 the 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 the merge.

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

//Person1 Object containing the attributes name & age
const person1 = 
{ 
  name : "Skay", 
  age : 32 
};

//Person2 Object containing the attributes name, age & occupation
const 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' variable
const name = 'Skay';

//Spread Operator extracts the characters from the String and assigns to an array
const 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 the array. So 1 is passed into a, 2 is passed into b, and 3 is passed into c.

//Array of numbers
const arr = [1,2,3];

//Arrow Function to add numbers
const 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 array
console.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 Object
const person = 
{
	name : 'Skay',
  age: 38,
  occupation: 'Web Developer',
	skills: 'HTML, CSS, JavaScript'
};

//Destructuring the Person object and assigning the values to name & age
//The attributes occupation & skills are automatically assigned to 'others'
//By using the spread operator
const { name, age, ...others } = person;

console.log(`Name is ${name}`); //Output -> Name is Skay
console.log(`Age is ${age}`); //Output -> Age is 38
console.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, filter, etc.

However, with the 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 the 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 the 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 the 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. Don't forget to connect with me on Twitter @skaytech.

Blog Articles

© Skay Tech 2020