Skip to content
blog
2 min read

Mastering Array Methods

Learn the most useful array methods in JavaScript: indexOf, push, pop, shift, unshift, splice, and slice for finding, adding, and removing items.

JavaScript arrays come with built-in methods for finding, adding, and removing items. These are the ones you’ll reach for constantly.

Finding Items

indexOf returns the index of the first matching item, or -1 if not found:

const fruits = ["apple", "banana", "cherry"];
fruits.indexOf("banana"); // 1
fruits.indexOf("grape"); // -1

includes is simpler when you just need a yes/no:

fruits.includes("apple"); // true

Adding Items

push adds to the end:

fruits.push("mango");
// ['apple', 'banana', 'cherry', 'mango']

unshift adds to the beginning:

fruits.unshift("avocado");
// ['avocado', 'apple', 'banana', 'cherry']

Removing Items

pop removes the last item and returns it:

const last = fruits.pop(); // 'cherry'

shift removes the first item and returns it:

const first = fruits.shift(); // 'apple'

splice — Add, Remove, or Replace at Any Position

splice(start, deleteCount, ...items) is the most flexible:

const nums = [1, 2, 3, 4, 5];
// Remove 2 items starting at index 1
nums.splice(1, 2); // returns [2, 3], array is now [1, 4, 5]
// Insert without removing
nums.splice(1, 0, "a", "b"); // [1, 'a', 'b', 4, 5]
// Replace
nums.splice(1, 1, 99); // replaces index 1 with 99

slice — Copy a Portion

slice(start, end) returns a new array without modifying the original:

const nums = [1, 2, 3, 4, 5];
nums.slice(1, 3); // [2, 3]
nums.slice(-2); // [4, 5] — last two items

splice mutates; slice does not. The naming is close enough to confuse everyone at least once.