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:
const in Array doesn’t define a constant array. It defines a constant reference to an array.
Simple example code.
<!DOCTYPE html> <html> <body> <script> const arr = ; arr.push("something"); // Allowed: add value to array console.log(arr) arr = "or other"; // Allowed: replace value in array console.log(arr) arr.length = 0; // Allowed: change array size console.log(arr) </script> </body> </html>
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’
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 = 7; // An element is not constant!
var myCars=new Array(); myCars="Saab"; myCars="Volvo"; myCars="BMW";
var myCars=new Array("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
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.
cool and helpfil