JavaScript Spread Operator

JavascriptWeb DevelopmentObject Oriented Programming

The JavaScript spread operator allows us to expand an array into individual array elements. To use the spread operator three dots (…) should be preceded by the array name.

Following is the code for the JavaScript spread operator −

Example

 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: 18px;
      font-weight: 500;
      color: red;
   }
   .result {
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>JavaScript Spread Operator</h1>
<div class="sample"></div>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button combine the two arrays using spread operator
into a new one
</h3>
<script>
   let resultEle = document.querySelector(".result");
   let sampleEle = document.querySelector(".sample");
   let arr1 = [1, 2, 3, 4, 5];
   let arr2 = ["A", "B", "C", "D", "E"];
   sampleEle.innerHTML = "arr1 = " + arr1 + "<br> arr2 = " + arr2;
   document.querySelector(".Btn").addEventListener("click", () => {
      let arr3 = [...arr1, ...arr2];
      resultEle.innerHTML = "arr3 = " + arr3;
   });
</script>
</body>
</html>

Output

On clicking the ‘CLICK HERE’ button −

raja
Published on 12-May-2020 09:25:25
Advertisements