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.
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.
indexOf returns the index of the first matching item, or -1 if not found:
const fruits = ["apple", "banana", "cherry"];fruits.indexOf("banana"); // 1fruits.indexOf("grape"); // -1includes is simpler when you just need a yes/no:
fruits.includes("apple"); // truepush adds to the end:
fruits.push("mango");// ['apple', 'banana', 'cherry', 'mango']unshift adds to the beginning:
fruits.unshift("avocado");// ['avocado', 'apple', 'banana', 'cherry']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(start, deleteCount, ...items) is the most flexible:
const nums = [1, 2, 3, 4, 5];
// Remove 2 items starting at index 1nums.splice(1, 2); // returns [2, 3], array is now [1, 4, 5]
// Insert without removingnums.splice(1, 0, "a", "b"); // [1, 'a', 'b', 4, 5]
// Replacenums.splice(1, 1, 99); // replaces index 1 with 99slice(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 itemssplice mutates; slice does not. The naming is close enough to confuse everyone at least once.