JavaScript Spread (...) Operator (with Example)

JavaScript Spread Operator: In this tutorial, we will learn about the JavaScript spread (...) operator with its usages and examples. By Siddhant Verma Last updated : July 29, 2023

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.

Example

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.

JavaScript Spread Operator with Objects

To use the spread operator with an object, you need to put the spread operator / three dots (...) before an object's name.

Example

This example demonstrates the use of the spread operator with an object.

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

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

The output of the above example is:

(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.

JavaScript Spread Operator: Important Use Cases

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

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

The output of the above example is:

{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?

1. JavaScript spread operator to initialize the object memory

You can also use the spread operator to initialize the memory of an object. Consider the below-given example to learn more about it.

Example

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

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

The output of the above example is:

{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.

2. JavaScript spread operator to convert an array-like object to an array

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.

Example

<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.

3. JavaScript spread operator to pass arguments to a method or a function

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.

Example

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.

JavaScript Tutorial »




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.