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>
    const arr = [];

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

    arr[0] = "or other";   // Allowed: replace value in array

    arr.length = 0;        // Allowed: change array size



JavaScript const array

An array declared with const cannot be reassigned:


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


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?


1: Regular:

 var myCars=new Array(); 

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

Your email address will not be published. Required fields are marked *