Skip to content

Spread and Rest operator in JavaScript

  • by

JavaScript uses three dots (...) for both the spread and rest operators. Even though they have the same syntax they differ in functions.

The rest operator (…) allows us to call a function with any number of arguments and then access those excess arguments as an array. The rest operator also allows us in destructuring array or objects.

var var_name = [...iterable]; 

The spread operator (…) allows us to expand an iterable like array into its individual elements.

function function_name(...arguments) {
    statements;
}

Spread and rest operator in JavaScript

Simple example code two arrays are defined and they’re merged into one using the spread operator (…). The merged array contains elements in the order they’re merged.

<!DOCTYPE html>
<html>
<body>
  <script>

   let arr = [2, 3, 4, 5];
   let arr1 = ["a", "b", "c", "d"];

   console.log("Concatenated ", [...arr, ...arr1]);

   //add the elements before 
   console.log(...arr,100)

   //copied 
   const obj = {
        f: "John",
        l: "King",
    };
    const obj2 = { ...obj };
    console.log(obj2);
   
 </script>
</body>
</html>

Output:

Spread and rest operator in JavaScript

Rest operator take multiple elements as arguments and compresses them into a single element or iterable. Further operations are performed on the iterable.

<script>

   function addArr(num, ...ar) {
    let sum = num;
    ar.forEach((item) => {
     sum += item;
   });
    console.log("Sum of the elements", sum);
  }

  addArr(44, 11, 35, 44, 22, 99);

</script>

Output: Sum of the elements 255

Do comment if you have any doubts or suggestions on this Js operator topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *