JavaScript Array Const

Declaring an array with const ensures the variable identifier cannot be reassigned, but the array contents remain mutable. This means you can still add, remove, or change elements within the array.

Key Topics

const Declaration

Use const when you do not want to reassign the variable that holds the array reference.

const fruits = ["Apple", "Banana"];
console.log(fruits);

Output

> ["Apple", "Banana"]

Explanation: The fruits array is declared with const, preventing reassignment but allowing element modification.

Modifying Array Contents

You can still modify, add, or remove elements from the array declared with const.

fruits.push("Cherry");
console.log(fruits);

Output

> ["Apple", "Banana", "Cherry"]

Explanation: The push() method adds "Cherry" to the end, and the array now has three elements.

Reassignment Not Allowed

You cannot reassign a const array to a new array reference.

// fruits = ["Grape", "Mango"]; // Error

Output

> TypeError: Assignment to constant variable.

Explanation: Reassigning the entire array is not allowed since fruits is declared with const. However, modifying the existing array contents is allowed.

JavaScript Usage in DOM

This DOM-based example shows how a const array can be manipulated and displayed on a webpage without reassigning the variable.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Array Const in DOM</title>
</head>
<body>
    <h1>Array Const Demo</h1>
    <button onclick="addFruit()">Add Fruit</button>
    <p id="output"></p>

    <script>
        const fruits = ["Apple", "Banana"];
        function addFruit() {
            fruits.push("Orange");
            document.getElementById("output").textContent = fruits.join(", ");
        }
    </script>
</body>
</html>

Key Takeaways

  • Const Array: The reference cannot change, but the contents can.
  • Modifications: Add or remove elements without reassigning.
  • Reassignment: Not possible for const arrays.
  • DOM Integration: Dynamically update array contents without changing the reference.