JS Array Const

Understanding const arrays and their behavior in JavaScript

🔒 What are Const Arrays?

Arrays declared with const cannot be reassigned, but their contents can still be modified. This is because const prevents reassignment of the variable, not mutation of the object it references.


const fruits = ["apple", "banana"];
fruits.push("orange");  // ✅ This works
console.log(fruits);    // ["apple", "banana", "orange"]
// fruits = [];         // ❌ This would cause an error
                                    

Const vs Let vs Var

🔒

const

Cannot be reassigned

const arr = [1, 2, 3];
arr.push(4);     // ✅ OK
// arr = [5, 6]; // ❌ Error
🔄

let

Can be reassigned

let arr = [1, 2, 3];
arr.push(4);     // ✅ OK
arr = [5, 6];    // ✅ OK
⚠️

var

Function-scoped, can be reassigned

var arr = [1, 2, 3];
arr.push(4);     // ✅ OK
arr = [5, 6];    // ✅ OK

🔹 What You CAN Do with Const Arrays

Even though the array is const, you can still modify its contents:

🔸 Adding Elements

const colors = ["red", "green"];

// All these methods work with const arrays
colors.push("blue");           // ["red", "green", "blue"]
colors.unshift("yellow");      // ["yellow", "red", "green", "blue"]
colors.splice(2, 0, "purple"); // ["yellow", "red", "purple", "green", "blue"]

console.log(colors); // ["yellow", "red", "purple", "green", "blue"]

🔸 Removing Elements

const numbers = [1, 2, 3, 4, 5];

numbers.pop();        // [1, 2, 3, 4]
numbers.shift();      // [2, 3, 4]
numbers.splice(1, 1); // [2, 4]

console.log(numbers); // [2, 4]

🔸 Modifying Elements

const fruits = ["apple", "banana", "orange"];

fruits[0] = "grape";           // ["grape", "banana", "orange"]
fruits[fruits.length - 1] = "kiwi"; // ["grape", "banana", "kiwi"]

console.log(fruits); // ["grape", "banana", "kiwi"]

Output:

colors: ["yellow", "red", "purple", "green", "blue"]

numbers: [2, 4]

fruits: ["grape", "banana", "kiwi"]

🔹 What You CANNOT Do with Const Arrays

You cannot reassign the entire array:

❌ These will cause errors:

const fruits = ["apple", "banana"];

// TypeError: Assignment to constant variable
// fruits = ["orange", "grape"];
// fruits = [];
// fruits = null;
// fruits = undefined;

✅ Instead, do this:

const fruits = ["apple", "banana"];

// Clear the array (keep the reference)
fruits.length = 0;           // []
// or
fruits.splice(0);            // []

// Replace all elements
fruits.push("orange", "grape"); // ["orange", "grape"]

🔹 Block Scope with Const

Const arrays have block scope, just like let:

const globalArray = [1, 2, 3];

if (true) {
    const blockArray = [4, 5, 6];
    console.log(globalArray); // ✅ [1, 2, 3] - accessible
    console.log(blockArray);  // ✅ [4, 5, 6] - accessible
}

console.log(globalArray); // ✅ [1, 2, 3] - accessible
// console.log(blockArray); // ❌ ReferenceError: blockArray is not defined

function myFunction() {
    const functionArray = [7, 8, 9];
    console.log(functionArray); // ✅ [7, 8, 9] - accessible
}

myFunction();
// console.log(functionArray); // ❌ ReferenceError: functionArray is not defined

Output:

Inside block: [1, 2, 3] and [4, 5, 6]

Outside block: [1, 2, 3] only

Inside function: [7, 8, 9]

🔹 Best Practices with Const Arrays

✅ Do:

  • Use const by default for arrays
  • Use descriptive names for const arrays
  • Initialize const arrays when declaring them
  • Use array methods to modify contents

❌ Don't:

  • Try to reassign const arrays
  • Declare const arrays without initialization
  • Use var for arrays (use const or let)
// ✅ Good practices
const userNames = ["John", "Jane", "Bob"];
const shoppingCart = [];

// Add items to cart
shoppingCart.push({name: "Laptop", price: 1000});
shoppingCart.push({name: "Mouse", price: 25});

// Remove item from cart
const itemIndex = shoppingCart.findIndex(item => item.name === "Mouse");
if (itemIndex > -1) {
    shoppingCart.splice(itemIndex, 1);
}

console.log(shoppingCart); // [{name: "Laptop", price: 1000}]

🔹 Const Arrays in Functions

Const arrays work perfectly in functions:

function processNumbers() {
    const numbers = [1, 2, 3, 4, 5];
    
    // Filter even numbers
    const evens = numbers.filter(num => num % 2 === 0);
    
    // Double the even numbers
    const doubled = evens.map(num => num * 2);
    
    return doubled;
}

const result = processNumbers();
console.log(result); // [4, 8]

// Function that modifies array parameter
function addToArray(arr, item) {
    arr.push(item);
    return arr;
}

const myArray = [1, 2, 3];
addToArray(myArray, 4);
console.log(myArray); // [1, 2, 3, 4]

Output:

result: [4, 8]

myArray: [1, 2, 3, 4]

🔹 When to Use Const vs Let for Arrays

Use const when:

  • You won't reassign the entire array
  • You want to prevent accidental reassignment
  • The array represents a fixed collection (most cases)

Use let when:

  • You need to reassign the entire array
  • You're conditionally assigning different arrays
  • You're working with algorithms that replace arrays
// Use const - array contents change, but not the reference
const todoList = [];
todoList.push("Buy groceries");
todoList.push("Walk the dog");

// Use let - entire array gets replaced
let sortedNumbers = [3, 1, 4, 1, 5];
if (ascending) {
    sortedNumbers = sortedNumbers.sort((a, b) => a - b);
} else {
    sortedNumbers = sortedNumbers.sort((a, b) => b - a);
}

🧠 Test Your Knowledge

What happens when you try to reassign a const array?