JavaScript Symbol.isConcatSpreadable symbol

JavascriptWeb DevelopmentObject Oriented Programming

The Symbol.isConcatSpreadable symbol is used to specify if a nested array should be flattened to its individual array elements or not when using the Array.prototype.concat() method.

Following is the code for Symbol.isConcatSpreadable symbol −

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;
   }
   div {
      font-size: 20px;
      font-weight: 500;
   }
   .result {
      color: red;
   }
</style>
</head>
<body>
<h1>JavaScript Symbol.isConcatSpreadable symbol</h1>
<div class="sample"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to concat the both array into a single one
</h3>
<div class="result">isConcatSpreadable = true</div>
<div class="result">isConcatSpreadable = False</div>
<script>
   let fillEle = document.querySelector(".sample");
   let result = document.querySelectorAll(".result");
   let ele = [1, 2, 3];
   let ele2 = ["A", "B", "C"];
   let concatArr;
   fillEle.innerHTML += ele + "<br>" + ele2 + "<br>";
   document.querySelector(".Btn").addEventListener("click", () => {
      concatArr = ele.concat(ele2);
      for (let x of concatArr.entries()) {
         result[0].innerHTML += x + " - ";
      }
      result.innerHTML += "<br><br>";
      ele2[Symbol.isConcatSpreadable] = false;
      concatArr = ele.concat(ele2);
      for (let x of concatArr.entries()) {
         result[1].innerHTML += x + " - ";
      }
   });
</script>
</body>
</html>

Output

On clicking the “CLICK HERE” button −

raja
Published on 08-May-2020 11:51:51
Advertisements