Computer >> Computer tutorials >  >> Programming >> Javascript

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

<!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 −

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

On clicking the ‘CLICK HERE’ button −

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