Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on. You've got this! 🚀
Array Methods: push, pop, shift, unshift, splice
These methods add and remove elements from arrays. push/pop work at the end, shift/unshift work at the beginning, and splice can add/remove anywhere. These are the fundamental mutation methods.
Mutating Array Methods
- push(item) - Add to end. Returns new length. Most common addition method
- pop() - Remove from end. Returns removed item
- unshift(item) - Add to beginning. Returns new length. Slower than push (shifts everything)
- shift() - Remove from beginning. Returns removed item
- splice(index, deleteCount, ...items) - Add/remove at any position. Most flexible
- These methods MUTATE - They change the original array. Use with caution
Array Mutation Code
const fruits = ["Apple", "Banana", "Cherry"];
// push - add to end
fruits.push("Date");
console.log(fruits); // ["Apple", "Banana", "Cherry", "Date"]
// pop - remove from end
const removed = fruits.pop();
console.log(removed); // "Date"
console.log(fruits); // ["Apple", "Banana", "Cherry"]
// unshift - add to beginning
fruits.unshift("Avocado");
console.log(fruits); // ["Avocado", "Apple", "Banana", "Cherry"]
// shift - remove from beginning
fruits.shift();
console.log(fruits); // ["Apple", "Banana", "Cherry"]
// splice - add/remove at position
// splice(startIndex, deleteCount, ...newItems)
fruits.splice(1, 0, "Blueberry"); // insert at index 1, delete 0
console.log(fruits); // ["Apple", "Blueberry", "Banana", "Cherry"]
fruits.splice(2, 1); // remove 1 item at index 2
console.log(fruits); // ["Apple", "Blueberry", "Cherry"]
fruits.splice(1, 1, "Grape", "Kiwi"); // replace 1 item with 2
console.log(fruits); // ["Apple", "Grape", "Kiwi", "Cherry"]Tip
Tip
Use spread to avoid mutating: const newArr = [...arr, newItem] instead of arr.push(newItem). Immutable operations are safer and required by React state management. Reserve push/splice for local variables only.
map/filter return new arrays; sort/splice mutate the original
Common Mistake
Warning
Confusing splice (mutates original, add/remove at position) with slice (creates new array copy). splice(1, 2) removes 2 items starting at index 1 from the original. slice(1, 3) returns a new array with elements at indices 1 and 2.
Practice Task
Note
Practice mutation methods: (1) Create an array of 5 items. (2) Add 2 items to the end with push, 1 to the beginning with unshift. (3) Remove from both ends with pop and shift. (4) Use splice to insert an item at index 2.
Quick Quiz
Key Takeaways
- These methods add and remove elements from arrays.
- push(item) - Add to end. Returns new length. Most common addition method
- pop() - Remove from end. Returns removed item
- unshift(item) - Add to beginning. Returns new length. Slower than push (shifts everything)