JavaScript

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JS Array Const


In JavaScript, the const keyword is commonly used to declare variables that should not be reassigned. However, when it comes to arrays, const behaves differently than it does with primitive values like numbers or strings. Understanding how const interacts with arrays is essential for writing robust and predictable JavaScript code.

This tutorial explores the behavior of const with arrays, demonstrates practical examples, highlights common mistakes, and shares best practices.

Why Understanding Const with Arrays Matters

Using const with arrays is important because:

  • It prevents accidental reassignment of the array variable.

  • It helps maintain the integrity of references to arrays.

  • It encourages safer coding practices in large projects.

  • It clarifies the distinction between modifying an array and reassigning it.

Without understanding this behavior, developers often encounter confusion when they try to modify arrays declared with const.

Declaring Arrays with Const

When you declare an array with const, you cannot reassign the variable to a completely new array:

const fruits = ["Apple", "Banana", "Cherry"];
fruits = ["Mango", "Orange"]; // Error: Assignment to constant variable

However, the contents of the array are mutable, meaning you can still add, remove, or modify elements:

const fruits = ["Apple", "Banana", "Cherry"];
fruits.push("Mango");
console.log(fruits); // ["Apple", "Banana", "Cherry", "Mango"]

fruits[1] = "Orange";
console.log(fruits); // ["Apple", "Orange", "Cherry", "Mango"]

This distinction is crucial: const locks the reference to the array, not the contents.

Modifying Const Arrays

Even though the variable cannot be reassigned, all array methods that mutate the array work perfectly:

Adding Elements

const numbers = [1, 2, 3];
numbers.push(4); // Add at end
numbers.unshift(0); // Add at beginning
console.log(numbers); // [0, 1, 2, 3, 4]

Removing Elements

numbers.pop();   // Removes last element
numbers.shift(); // Removes first element
console.log(numbers); // [1, 2, 3]

Changing Elements

numbers[1] = 20;
console.log(numbers); // [1, 20, 3]

Using Splice

numbers.splice(1, 1, 50, 60); // Remove 1 element at index 1, add 50 and 60
console.log(numbers); // [1, 50, 60, 3]

Sorting

numbers.sort((a, b) => b - a);
console.log(numbers); // [60, 50, 3, 1]

Reversing

numbers.reverse();
console.log(numbers); // [1, 3, 50, 60]

Why Arrays Declared with Const Are Useful

  • Safety: You cannot accidentally assign the variable to a completely different array.

  • Predictability: Functions or modules that receive the array know that the reference will remain consistent.

  • Clarity: It communicates intent to other developers that the variable should not be reassigned.

Practical Examples

Example 1: Managing a Todo List

const todos = ["Write report", "Email client"];
todos.push("Schedule meeting");
todos[0] = "Complete report";
console.log(todos); // ["Complete report", "Email client", "Schedule meeting"]

Example 2: Storing Scores

const scores = [85, 90, 78];
scores.push(95); // Add new score
scores[1] = 92;  // Update score
console.log(scores); // [85, 92, 78, 95]

Example 3: Immutable Reference

const colors = ["Red", "Green"];
// colors = ["Blue", "Yellow"]; // Error: cannot reassign

colors.push("Blue"); // Allowed
console.log(colors); // ["Red", "Green", "Blue"]

Example 4: Using Const Arrays in Functions

const names = ["Emma", "Lily", "Sophia"];

function addName(newName) {
  names.push(newName);
}

addName("Olivia");
console.log(names); // ["Emma", "Lily", "Sophia", "Olivia"]

The array reference stays constant, but the contents can change dynamically.

Common Mistakes

  • Attempting to reassign a const array:

const fruits = ["Apple", "Banana"];
fruits = ["Mango"]; // ❌ Error
  • Confusing const immutability with object immutability. const only prevents reassignment, not content modification.

  • Assuming const arrays cannot be modified by methods like push(), pop(), or splice().

  • Forgetting that nested objects inside a const array are also mutable.

Best Practices

  • Use const by default for arrays that should not be reassigned.

  • Use let only when you plan to reassign the array variable entirely.

  • For deep immutability, consider using methods that return new arrays (like map(), filter(), or slice()) or libraries like Immutable.js.

  • Document intent clearly: const signals that the variable reference should remain constant, even if the contents are mutable.

  • Avoid mutating arrays passed to functions unless intentional; prefer creating new arrays for safer, functional-style code.

Summary of JS Array Const

Declaring arrays with const in JavaScript locks the reference to the array, ensuring it cannot be reassigned, but allows full modification of its contents. This behavior provides safety, clarity, and flexibility, making const arrays ideal for most use cases. By understanding how const interacts with arrays, developers can write predictable and maintainable code while leveraging array methods to manage dynamic data effectively. Proper usage of const promotes clean coding practices, prevents accidental reassignment, and supports robust application development.


Practice Questions

Q1. How do you declare an array with constant reference in JavaScript?

Q2. Can you change the values inside a const declared array?

Q3. What happens if you try to reassign a new array to a const variable?

Q4. Is it allowed to use .push() or .pop() on a const array?

Q5. How do you update the second value in const numbers = [1, 2, 3]?

Q6. Can you use splice() on a const array?

Q7. Which method will throw an error with const arrays: push() or reassignment?

Q8. What is the difference between let and const when used with arrays?

Q9. Why is const preferred for arrays in many cases?

Q10. What is the output of modifying a const array’s element?


Try a Short Quiz.

No quizzes available.


JavaScript

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top