Rest and Spread operators in JavaScript


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.

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

Example

Following is the code showing the rest and spread operator in JavaScript −

 Live Demo

<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .sample, .result {
      font-size: 20px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>JavaScript Rest and spread operator</h1>
<div class="sample"></div>
<div style="color: green;" class="result"></div&g;
<button class="btn">Spread Operator</button>
<h3>
Click on the above button to concatenate array using spread operator
</h3>
<button class="btn">Rest Operator</button>
<div style="color: green;" class="result"></div>
<h3>
Click on the above button to add some numbers using rest operator
</h3>
<script>
   let sampleEle = document.querySelector(".sample");
   let btnEle = document.querySelectorAll(".btn");
   let resEle = document.querySelectorAll(".result");
   let arr = [2, 3, 4, 5];
   let arr1 = ["a", "b", "c", "d"];
   sampleEle.innerHTML = "arr = " + arr + "<br> arr1 = " + arr1;
   function addArr(num, ...ar) {
      let sum = num;
      ar.forEach((item) => {
         sum += item;
      });
      resEle[1].innerHTML = "Sum of the elements = " + sum;
   }
   btnEle[0].addEventListener("click", () => {
      resEle[0].innerHTML = "Concatenated array = " + [...arr, ...arr1];
   });
   btnEle[1].addEventListener("click", () => {
      addArr(44, 11, 35, 44, 22, 99);
   });
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the “Spread Operator” button −

On clicking the “Rest Operator” button −

Updated on: 15-Jul-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements