Home » JavaScript Tutorial

Spread Operator in JavaScript

JavaScript Spread Operator: Here, we are going to learn about the Spread operator in JavaScript with its usages and examples.
Submitted by Siddhant Verma, on October 11, 2019

JavaScript Spread Operator

The spread operator came out in ES6 and has great functionality for arrays in JavaScript. With a major update in ES9, the spread operator is now extended to objects in addition to arrays. In this article, we'll talk about the spread operator, how to use it and where to use it.

The spread operator looks something like ... and allows us to spread the items contained in an iterable. An iterable can be visualized as anything on which we can add loops to traverse them like arrays, strings, objects, etc.

let arr=[1,2,3,4];
console.log(arr); 	//(4) [1, 2, 3, 4]
console.log(...arr); 	//1 2 3 4

Notice how the first console.log() gets us the whole array whereas the second one just gives us the elements of the array? We have used the spread operator to spread the values of the array since each value of the array can be iterated over. This is a very basic use case of the spread operator.

Using the spread operator with objects

var people=[
    {name: 'Fuzzy', age:20},
    {name: 'Stella', age:18},
    {name: 'Banku' , age: 14}
]

console.log(people)
console.log(...people);

Output

(3) [{…}, {…}, {…}]	 
{name: "Fuzzy", age: 20} {name: "Stella", age: 18} {name: "Banku", age: 14}

We have used the spread operator to spread over the values of an array which is essentially an array of objects.

Important Use Cases

const player={
    strength: 50,
    agility: 40,
    health: 100
}

const player2=player;
player2.health=0;
console.log(player2);
console.log(player);

Output

{strength: 50, agility: 40, health: 0}
{strength: 50, agility: 40, health: 0}

We have an object which gives us some properties of a player like strength, agility, health, etc. We declare another object player2 and set its health to 0. So now player2 will have a health of 0. However, when we see the health of our original player object, it also becomes 0. How did this happen? We only changed the health of player2, player should have stayed unaffected.

The answer lies in the fact that objects are non-primitive data types. When we created player2 we referenced it to the same memory location as that of player. Hence both share the same values and changing one changes the properties of the other. You can confirm this by,

    player===player2;   //true

JavaScript has treated both the objects as one. How to tackle this problem?

Spread operator to initialize the object memory

const player={
    strength: 50,
    agility: 40,
    health: 100
}

const player2={...player};
player2.health=0;
console.log(player2);
console.log(player);

Output

{strength: 50, agility: 40, health: 0}
{strength: 50, agility: 40, health: 100}

Now both player and player2 refer to different memory locations. We have used the spread operator to destructure the player object and cloned or created a copy of the player object and assigned it to player2. Whatever changes we make for player2 are changed only in this copy and the original values remain unchanged for the player object.

Thus, this way we can easily clone arrays and objects without worrying about immutability.

Another important use case of the spread operator is to convert array-like objects to arrays. We know that querying the DOM does not give us an object or an array, it gives us an array-like object like a nodelist or an HTML collection. We can easily convert this to an array using the spread operator.

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="styles.css">
    <title>Events in DOM</title>

</head>

<body>

    <div class="player">
        <p>Fuzzy </p>
    </div>
    <div class="player">
        <p>Stella </p>
    </div>
    <div class="player">
        <p>Banku</p>
    </div>
    <div class="player">
        <p>Garry </p>
    </div>
    <div class="player">
        <p>Damon </p>
    </div>
    <div class="player">
        <p>Reiki </p>
    </div>
    <div class="player">
        <p>Leila</p>
    </div>

</body>

<script>
    const players = document.getElementsByClassName('.player');
    console.log(players);

    const playersArr = [...players];
    console.log(playersArr);
</script>

</html>

Output

HTMLCollection []
 []

The first one returns us an HTML Collection whereas the second one returns us an array. Thus we have converted an HTML collection into an array.

    players.forEach
    //undefined
    playersArr.forEach;
    //ƒ forEach() { [native code] }

And we can also easily use the forEach method on our new array.

Sometimes using the spread operator for passing in arguments to a method or a function comes in very handy. Let's say we have an array of numbers and we have to find the maximum out of all of them. You might say one approach to this could be looping through all elements and comparing every two consecutive elements or simply sorting the element, but if we use the inbuilt max function in the Math object it'll save us some considerable lines of code.

var arr=[8,-12,866,7,-44,0,81,11,-3123,1283];
console.log(Math.max(...arr)); 
//Output: 1283

Thus the spread operator comes in handy in a lot of scenarios especially in cloning non-primitive data types, converting array-like objects to arrays and passing arguments to methods and functions.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.