JavaScript provides a vast array of prototype methods to add, remove, slice, splice, and flatten array elements. Understanding whether a method mutates the original array or returns a new copy is critical for predictable state management.
flowchart TD
Methods["Array Methods"] --> Mutating["Mutating (In-place): push, pop, shift, unshift, splice, sort"]
Methods --> NonMutating["Non-Mutating (Returns Copy): slice, concat, flat, toSpliced"]
| Method | Operates On | Returns | Mutates Original? | Description |
|---|---|---|---|---|
push(...items) |
End | New length |
Yes | Adds items to end of array. |
pop() |
End | Removed item | Yes | Removes and returns last element. |
unshift(...items) |
Beginning | New length |
Yes | Adds items to start of array. |
shift() |
Beginning | Removed item | Yes | Removes and returns first element. |
splice(start, count, ...items) |
Any Index | Removed items | Yes | Removes/replaces existing elements in-place. |
slice(start, end) |
Index Range | Sub-array | No | Extracts shallow copy of section of array. |
flat(depth) |
Sub-arrays | Flattened Array | No | Flattens nested arrays to specified depth. |
// Demonstrating Mutating vs Non-Mutating Array Methods
// 1. Mutating Stack/Queue Operations
const queue = ["Task 1", "Task 2"];
queue.push("Task 3"); // Add to end
console.log("After push:", queue);
const completedTask = queue.shift(); // Remove from start
console.log(`Completed: ${completedTask}, Remaining:`, queue);
// 2. In-Place Modification with splice()
const items = ["A", "B", "C", "D"];
const removedItems = items.splice(1, 2, "X", "Y"); // At index 1, delete 2 items, insert "X", "Y"
console.log("Mutated Items after splice:", items); // ["A", "X", "Y", "D"]
console.log("Removed items:", removedItems); // ["B", "C"]
// 3. Non-Mutating Sub-Array Extraction with slice()
const originalNumbers = [10, 20, 30, 40, 50];
const subSection = originalNumbers.slice(1, 4); // Extracts indices 1, 2, 3
console.log("Extracted subSection (slice):", subSection); // [20, 30, 40]
console.log("Original Numbers (Unchanged):", originalNumbers);
// 4. Flattening Nested Arrays with flat()
const nested = [1, [2, [3, 4]]];
console.log("Flattened Depth 1:", nested.flat(1)); // [1, 2, [3, 4]]
console.log("Flattened Infinite:", nested.flat(Infinity)); // [1, 2, 3, 4]
slice, concat, spread [...arr]) or modern ES2023 helpers (toSpliced()).shift() and unshift() Performance: Adding or removing elements from the beginning of large arrays requires re-indexing all elements ($O(n)$ complexity).flat() Depth is 1: Calling flat() without arguments flattens only 1 level deep. Pass Infinity for deeply nested arrays.Write a function removeElementAtIndex(arr, index) that returns a new array with the item at index removed without mutating arr.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.