-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
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 Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
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.
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.
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.
Even though the variable cannot be reassigned, all array methods that mutate the array work perfectly:
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]
numbers.pop(); // Removes last element
numbers.shift(); // Removes first element
console.log(numbers); // [1, 2, 3]
numbers[1] = 20;
console.log(numbers); // [1, 20, 3]
numbers.splice(1, 1, 50, 60); // Remove 1 element at index 1, add 50 and 60
console.log(numbers); // [1, 50, 60, 3]
numbers.sort((a, b) => b - a);
console.log(numbers); // [60, 50, 3, 1]
numbers.reverse();
console.log(numbers); // [1, 3, 50, 60]
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.
const todos = ["Write report", "Email client"];
todos.push("Schedule meeting");
todos[0] = "Complete report";
console.log(todos); // ["Complete report", "Email client", "Schedule meeting"]
const scores = [85, 90, 78];
scores.push(95); // Add new score
scores[1] = 92; // Update score
console.log(scores); // [85, 92, 78, 95]
const colors = ["Red", "Green"];
// colors = ["Blue", "Yellow"]; // Error: cannot reassign
colors.push("Blue"); // Allowed
console.log(colors); // ["Red", "Green", "Blue"]
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.
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.
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.
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.
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?
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 Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
