Skip to content

JavaScript const array | Code

Declaring a JavaScript Array as const only means that you can’t assign a new value to that variable (Array) once a value has been assigned:

const array = [];

array = []; // Not allowed: assignment to constant variable

Declaring an array as const has no bearing on what you can do with the contents of the actual array:

Using keyword const in Array doesn’t define a constant array. It defines a constant reference to an array.

JavaScript const array

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
    const arr = [];

    arr.push("something"); // Allowed: add value to array
    console.log(arr)

    arr[0] = "or other";   // Allowed: replace value in array
    console.log(arr)

    arr.length = 0;        // Allowed: change array size
    console.log(arr)

  </script>
</body>
</html>

Output:

JavaScript const array

An array declared with const cannot be reassigned:

  <script>

    const cars = ["A", "B", "C"];
    cars = ["X", "Y", "Z"];

  </script>

Output: Uncaught TypeError: invalid assignment to const ‘cars’

With Object.freeze you can prevent values from being added or changed on the object:

'use strict';
const vector = Object.freeze([1, 2, 3, 4]);

vector[2] = 7; // An element is not constant!

How to initialize a JavaScript array with constant values?

Answer:

1: Regular:

 var myCars=new Array(); 
 myCars[0]="Saab";       
 myCars[1]="Volvo";
 myCars[2]="BMW";

2: Condensed:

 var myCars=new Array("Saab","Volvo","BMW");

3: Literal:

 var myCars=["Saab","Volvo","BMW"];

Do comment if you have any doubts or suggestions on this Js Array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

1 thought on “JavaScript const array | Code”

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading