Mutator methods directly modify the contents and length of the original array in memory. Understanding these operations is essential for implementing classical computer science data structures like Stacks (LIFO) and Queues (FIFO).
const queue = ["User1", "User2"];
// 1. push(): Appends to the END (O(1) time complexity)
queue.push("User3"); // ["User1", "User2", "User3"]
// 2. pop(): Removes and returns the LAST element (O(1))
const lastUser = queue.pop(); // Returns "User3"
// 3. unshift(): Prepends to the START (O(N) - shifts all indices!)
queue.unshift("VIP_User"); // ["VIP_User", "User1", "User2"]
// 4. shift(): Removes and returns the FIRST element (O(N))
const firstUser = queue.shift(); // Returns "VIP_User"
splice(startIndex, deleteCount, ...items)The splice() method can delete elements, insert new elements, or replace elements at any arbitrary index:
const numbers = [10, 20, 30, 40, 50];
// DELETION: Remove 2 elements starting at index 1
const deleted = numbers.splice(1, 2);
console.log("Deleted:", deleted); // [20, 30]
console.log("Remaining:", numbers); // [10, 40, 50]
// INSERTION: Insert at index 1 without deleting (deleteCount = 0)
numbers.splice(1, 0, 99, 100);
console.log("After Insertion:", numbers); // [10, 99, 100, 40, 50]
// REPLACEMENT: Replace index 2 with a new value
numbers.splice(2, 1, 999);
console.log("After Replacement:", numbers); // [10, 99, 999, 40, 50]
const scores = [10, 5, 40, 25, 100];
// THE BUG: Default alphabetical sort
scores.sort();
console.log("Alphabetical Sort:", scores); // [10, 100, 25, 40, 5] (WRONG!)
// THE FIX: Numeric Compare Function (a - b for Ascending)
scores.sort((a, b) => a - b);
console.log("Ascending Order:", scores); // [5, 10, 25, 40, 100] (CORRECT!)
// Descending Order (b - a)
scores.sort((a, b) => b - a);
console.log("Descending Order:", scores); // [100, 40, 25, 10, 5]
Exam Question: "How do you implement a Stack in JavaScript using native array methods?"
class Stack {
constructor() { this.items = []; }
push(element) { this.items.push(element); }
pop() { return this.items.pop(); }
peek() { return this.items[this.items.length - 1]; }
isEmpty() { return this.items.length === 0; }
}
How do you transform, filter, and aggregate array data without mutating the original? Proceed to: JavaScript Array Iteration: map, filter & reduce →
Accelerate your JavaScript mastery by studying these tightly connected core tutorials:
Declaration, length, and index access.
forEach, map, filter, reduce, find, some.
Pure functions and immutable operations.