Explain the benefits of spread syntax & how it is different from rest syntax in ES6?


In the ES6 version of JavaScript, spread syntax is introduced as a very powerful feature. We can use the spread syntax to expand the array or objects into the variable of the same data type.

For example, before the spread syntax was introduced in the ES6, developers were using the for loop to copy all elements of one array to another array. Can you copy all elements of one array to another by writing one linear code using the spread syntax rather than writing the 5 to 7 lines of code using the for loop? Yes, you heard right!

Here, we will learn different use cases of the spread syntax in this tutorial. Also, we will learn how it is different from the rest syntax at the end of the tutorial.

Spread Syntax

The spread synatx in JavaScript is a syntax that allows an iterable object, such as an array or object, to be expanded into individual variables or elements.

Users can follow the syntax below to use the spread syntax to expand the iterable object.

let array = [10, 40, 7, 345];
let array2 = [...array];

In the above syntax, we are copying all the elements of the ‘array’ iterable to the array2 variable.

Benefits of Spread Syntax

There are some benefits or features of using spread syntax −

  • Copying arrays or objects,

  • Merging arrays or objects, and

  • Passing multiple elements as function arguments.

Let’s look at different examples for each of the above features of the spread syntax.

Example

Copying arrays using spread syntax

We have used the spread synatx in this example to copy the elemetns of an array to another array. You can see the one-linear code copies all array elements into array2.

<html>
   <body>
      <h2>Using the spread syntax to copy one array to another</h2>
      <div id="output"></div>
      <script>
         let output = document.getElementById("output");
         let array1 = [10, 40, 7, 345];
         output.innerHTML += "Original array: " + array1 + "</br>";
         
         // copy array using spread syntax
         let array2 = [...array1];
         output.innerHTML += "Copied array: " + array2 + "</br>";
      </script>
   </body>
</html>

Example

Merging arrays or objects using spread syntax

We merge the array1 and array2 using the spread syntax inside the array1 without using the concat() method of JavaScript. Also, while merging both arrays, we changed the order of array elements.

<html>
<body>
   <h2>Using the spread syntax to <i> copy one array to another</i></h2>
   <div id="output"></div>
   <script>
      let output = document.getElementById("output");
      let array = [10, 40, 7, 345];
      output.innerHTML += "Array 1: " + array + "</br>";
      let array2 = ["Hi, Hello"];
      output.innerHTML += "Array 2: " + array2 + "</br>";
      array = [...array2, ...array];
      output.innerHTML += "After merging the array2 and array1: " + array + "<br/>";
   </script>
</body>
</html>

Example

Passing multiple elements as function arguments using spread syntax

In this example, we have created the add() function, which takes three values as a parameter and returns the sum of all three parameters. We have created the array, which contains three values. We have passed all array elements to the add() function as an argument using the spread syntax.

<html>
   <body>
      <h2>Using the spread syntax</h2>
      <p> Passing multiple array elements as a function argument </p>
      <div id="output"></div>
      <script>
         let output = document.getElementById("output");
      
         // function to get a sum of 3 values
         function add(param1, param2, param3) {
            return param1 + param2 + param3;
         }
         let values = [50, 54, 72];
      
         // passed array values using the spread syntax
         let result = add(...values);
         output.innerHTML += "The sum of 3 array values: " + result + "</br>";
      </script>
   </body>
</html>

Example

Copying objects using spread synatx

In the example below, we have created the sample_obj object, which contains the different key-value pairs. Using the spread syntax, we have copied all the key-value pairs of the sample_obj to copy_object.

As the object is iterable, we can use the spread syntax to expand the object.

<html>
   <body>
      <h2>Using the spread syntax to <i>create a copy of the object.</i></h2>
      <div id="output"></div>
      <script>
         let output = document.getElementById("output");
         let sample_obj = {
            name: "Shubham",
            age: 22,
            hobby: "writing",
         };
         let copy_object = {
            ...sample_obj,
         };
         output.innerHTML += "The values of the copy_object are " + copy_object.name + " , " +copy_object.age + " , " + copy_object.hobby +  "</br>";
      </script>
   </body>
</html>

Rest Syntax

In JavaScript, the syntax of the rest syntax is the same as the spread syntax. We can use the rest syntax to collect elements in the single array or iterable, unlike expanding using the spread syntax.

Generally, developers use the spread syntax with the function parameters when the total number of function parameters is not defined or to pass the optional parameters.

Syntax

Users can follow the syntax below to use the rest syntax.

function func(...params){
   
   //params are the array of all arguments passed while calling the function
   
   //users can access the params like params[0], params[1], params[2], ...
}

In the above syntax, we collect all the function parameters in the params array.

Example

In this example, we have created the array of strings and passed all array elements as an argument of the mergeString() function using the spread syntax.

Using the rest syntax, we have collected all parameters of the mergeString() function in the params array. We iterate through the params array and concatenate every element of the params array in the finalString variable.

<html>
   <body>
      <h2>Using the rest syntax to collect function parameters</h2>
      <div id="output"></div>
      <script>
         let output = document.getElementById("output");
         
         // used the rest syntax to collect params
         function mergeString(...params) {
            let finalString = "";
            
            // Iterating through the array of params
            for (let param of params) {
               finalString += param;
               output.innerHTML += "Parameter: " + param + "<br>";
            }
            output.innerHTML += "The string after merging: " + finalString;
         }
         let strings = ["Welcome", "to", "the", "TutorialsPoint!"];
         
         // used the spread syntax to pass all elements of // the strings array as an argument.
         mergeString(...strings);
      </script>
   </body>
</html>

Users can clearly understand the difference between the rest and spread syntaxs via the above example.

Difference betweern Spread and Rest Syntax in ES6:

The spread syntax is different from the rest syntax, which is used to collect multiple elements or properties into an array. The spread syntax allows for the expansion of elements, while the rest syntax allows for the collection of elements.

Examples of using the spread syntax include copying an array to another array, merging two arrays, passing multiple array elements as function arguments, and copying the properties of one object to another object.

Examples of using the rest syntax include collecting elements, function parameters, etc.

The following table highlights how the spread syntax is different from rest syntax in ES6 −

Spread syntax

Rest Syntax

We can use the spread syntax to expand the iterable.

We can use the rest syntax to collect elements and make iterable of all collected elements.

We can expand the data in array or object format using it.

We can collect all elements in the required format.

We can use it to pass arguments inside the function.

We can use it to collect function parameters or to define the optional parameters.

Conclusion

The spread syntax in JavaScript is a syntax that allows an iterable object, such as an array or object, to be expanded into individual variables or elements.

The spread syntax is different from the rest syntax. The spread syntax is a useful feature for performing tasks such as copying arrays, merging arrays or objects, and passing multiple elements as function arguments.

The rest syntax is useful for performing tasks such as collecting multiple elements or properties into an array.

Updated on: 05-Jan-2023

131 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements