Topic 43 of 87
Array Mutators
Overview
Mutator methods modify (mutate) the original array directly in memory. While push and pop mutate the end of the array, shift and unshift mutate the beginning.
The most powerful mutator is splice(), which can add, remove, or replace elements at ANY specific index in the array.
Syntax
Shift and Unshift (The Beginning)
javascript
const queue = ["User2", "User3"];
// unshift() adds to the FIRST position
queue.unshift("User1");
// ["User1", "User2", "User3"]
// shift() removes the FIRST element and returns it
const firstUser = queue.shift();
console.log(firstUser); // "User1"The Almighty Splice
javascript
const fruits = ["Apple", "Banana", "Mango"];
// splice(insertAtIndex, deleteCount, newItems...)
// 1. Remove 1 item at index 1 ("Banana")
fruits.splice(1, 1); // fruits is now ["Apple", "Mango"]
// 2. Insert "Kiwi" at index 1 without deleting anything
fruits.splice(1, 0, "Kiwi"); // ["Apple", "Kiwi", "Mango"]
// 3. Replace "Mango" (index 2) with "Orange"
fruits.splice(2, 1, "Orange"); // ["Apple", "Kiwi", "Orange"]Common Pitfalls
- Using
shift()andunshift()on massive arrays (e.g., 100,000 items). Because they modify the very beginning of the array, the JavaScript engine has to re-index every single subsequent element in memory. This is computationally expensive! Usepush/popwhen order doesn't strictly matter.
Interview Questions
Q:
What is the difference between
slice() and splice()?A:
slice() is pure: it creates a new shallow copy of a portion of an array without modifying the original. splice() is a mutator: it directly changes the original array by removing, replacing, or adding elements.
Real-World Example
Removing a specific task from a Todo List when the user clicks 'Delete'.
example
javascript
function deleteTask(index) {
todos.splice(index, 1); // Removes 1 item at the given index
renderTodos();
}Check Your Knowledge
Test your understanding of Array Mutators with these quick questions.