How to create a constant array in JavaScript? Can we change its values? Explain.


To create a const array in JavaScript we need to write const before the array name. The individual array elements can be reassigned but not the whole array.

Following is the code to create a constant array in JavaScript.

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;
   }
   .result,.sample {
      font-size: 20px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>Const array in JavaScript</h1>
<div class="sample"></div>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to change array values and reassign the array later
</h3>
<script>
   let sampleEle = document.querySelector(".sample");
   let resEle = document.querySelector(".result");
   const arr = [22, 33, 44, 55];
   sampleEle.innerHTML = "Original Array = " + arr;
   document.querySelector(".Btn").addEventListener("click", () => {
      (arr[0] = 44), (arr[1] = 99), (arr[2] = 0);
      resEle.innerHTML += "Changing array elements value" + arr + '<br>';
      try {
         arr = [11, 11, 11, 11];
      }
      catch (err) {
         resEle.innerHTML += "Trying to reassign const array = " + err;
      }
   });
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the ‘CLICK HERE’ button −

Updated on: 16-Jul-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements