JavaScript Array Const - JavaScript Const Array



ECMAScript 2015 (ES6)

  • In 2015, JavaScript introduced an important new keyword: const.
  • It has become a common practice to declare arrays using const.
const cars = ["Saab", "Volvo", "BMW"];

Cannot be Reassigned

  • An array declared with const cannot be reassigned.
const cars = ["Saab", "Volvo", "BMW"];
cars = ["Toyota", "Volvo", "Audi"];    // ERROR

Arrays are Not Constants

  • The keyword const is a little misleading.
  • It does NOT define a constant array. It defines a constant reference to an array.
  • Because of this, we can still change the elements of a constant array.
// You can create a constant array:
const cars = ["Saab", "Volvo", "BMW"];

// You can change an element:
cars[0] = "Toyota";

// You can add an element:
cars.push("Audi");

Sample Code

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript const</h2>

<p>Declaring a constant array does NOT make the elements unchangeable:</p>

<p id="demo"></p>

<script>
// Create an Array:
const cars = ["Saab", "Volvo", "BMW"];

// Change an element:
cars[0] = "Toyota";

// Add an element:
cars.push("Audi");

// Display the Array:
document.getElementById("demo").innerHTML = cars; 
</script>

</body>
</html>

Output

JavaScript const
Declaring a constant array does NOT make the elements unchangeable:
Toyota,Volvo,BMW,Audi

Browser Support

  • The const keyword is not supported in Internet Explorer 10 or earlier.

Assigned when Declared

  • JavaScript const variables must be assigned a value when they are declared.
  • Meaning: An array declared with const must be initialized when it is declared.
  • Using const without initializing the array is a syntax error:

Example

  • This will not work:
const cars;
cars = ["Saab", "Volvo", "BMW"];

Redeclaring Arrays

  • Redeclaring an array declared with var is allowed anywhere in a program.
var cars = ["Volvo", "BMW"];   // Allowed
var cars = ["Toyota", "BMW"];  // Allowed
cars = ["Volvo", "Saab"];      // Allowed

Related Searches to JavaScript Array Const - JavaScript Const Array