Tutorials JavaScript Array Methods
Ch 31 / 78
Chapter 31 Beginner 11 min read JavaScript

Array Methods

JavaScript arrays come packed with powerful built-in methods for adding, removing, searching, sorting, transforming, and combining elements. Knowing these methods deeply — and understanding which ones mutate the original vs which return a new array — is one of the most important skills in everyday JavaScript.

What you'll learn
Mutating vs non-mutating (pure) methods
Adding & removing — push, pop, shift, unshift, splice
Searching — indexOf, lastIndexOf, includes, find, findIndex
Transforming — slice, concat, flat, flatMap, fill, copyWithin
Sorting & reversing — sort, reverse, toSorted, toReversed
Checking — every, some, Array.isArray, at

Mutating vs Pure Methods

The most important concept to understand before learning individual methods is whether they mutate (change) the original array or return a new array leaving the original intact. Mutating methods can cause subtle bugs when the same array is referenced in multiple places:

Mutating — changes original
.push() Adds to the end, returns new length
.pop() Removes from the end, returns removed item
.shift() Removes from the start, returns removed item
.unshift() Adds to the start, returns new length
.splice() Adds/removes at any index
.sort() Sorts in place, returns same array
.reverse() Reverses in place, returns same array
.fill() Fills a range with a static value
Pure — returns new array / value
.slice() Returns a portion as a new array
.concat() Merges arrays into a new one
.map() Transforms each element, new array
.filter() Keeps matching elements, new array
.flat() / .flatMap() Flattens nested arrays, new array
.toSorted() Sorted copy (ES2023)
.toReversed() Reversed copy (ES2023)
.toSpliced() Spliced copy (ES2023)
Tip
In modern React and functional-style code, prefer non-mutating methods to avoid unexpected side effects. Instead of arr.sort(), use [...arr].sort() or ES2023's arr.toSorted() to keep the original intact.

Adding & Removing Elements

These are the workhorse methods for modifying array contents. They all mutate the original array, so use spread ([...arr]) or slice() to clone first if needed:

.push(...items)
Appends one or more items to the end of the array. Returns the new length. Most common way to add to an array.
.pop()
Removes and returns the last element. Returns undefined on an empty array. Classic stack operation.
.unshift(...items)
Prepends one or more items to the start. Returns the new length. Slower than push on large arrays (shifts all existing elements).
.shift()
Removes and returns the first element. Classic queue operation. Also slower than pop on large arrays.
.splice(start, deleteCount, ...items)
Swiss-army knife — removes deleteCount elements starting at start, and optionally inserts new items in their place. Returns an array of deleted elements.
JavaScript — Add & Remove
const fruits = ["apple", "banana", "cherry"];  
// push — add to end fruits.push("date"); console.log(fruits); // ["apple","banana","cherry","date"] // pop — remove from end const last = fruits.pop(); console.log(last); // "date" console.log(fruits); // ["apple","banana","cherry"] // unshift — add to start fruits.unshift("avocado"); console.log(fruits); // ["avocado","apple","banana","cherry"] // shift — remove from start const first = fruits.shift(); console.log(first); // "avocado" // splice — remove 1 element at index 1 const removed = fruits.splice(1, 1); console.log(removed); // ["banana"] console.log(fruits); // ["apple","cherry"] // splice — insert without removing fruits.splice(1, 0, "blueberry", "mango"); console.log(fruits); // ["apple","blueberry","mango","cherry"] // splice — replace elements fruits.splice(0, 2, "kiwi"); console.log(fruits); // ["kiwi","mango","cherry"]

Searching & Checking

These methods help you find elements or verify conditions across an array. Most return either an index, the element itself, or a boolean — and all are non-mutating:

.indexOf(item, from?)
Returns the first index where item is found using strict equality. Returns -1 if not found.
[3,1,3].indexOf(3) → 0
.lastIndexOf(item, from?)
Returns the last index where item is found, searching backwards. Returns -1 if not found.
[3,1,3].lastIndexOf(3) → 2
.includes(item, from?)ES7
Returns true if the array contains the item. Unlike indexOf, correctly handles NaN.
[1,NaN].includes(NaN) → true
.find(fn)ES6
Returns the first element that passes the callback test. Returns undefined if none match.
arr.find(x => x > 5)
.findIndex(fn)ES6
Returns the index of the first element that passes the callback. Returns -1 if none match.
arr.findIndex(x => x > 5)
.findLast(fn)ES2023
Like find but searches from the end of the array backwards.
arr.findLast(x => x > 5)
.every(fn)
Returns true if all elements pass the callback test. Short-circuits on first failure.
[2,4,6].every(x=>x%2===0) → true
.some(fn)
Returns true if at least one element passes the callback. Short-circuits on first match.
[1,3,4].some(x=>x%2===0) → true
JavaScript — Searching & Checking

Slicing, Copying & Combining

These methods extract portions of arrays or combine multiple arrays together — all without modifying the originals:

.slice(start?, end?)
Returns a shallow copy of a portion of the array from start up to (not including) end. Negative indices count from the end. No arguments → full copy.
.concat(...arrays)
Returns a new array formed by merging the original with additional arrays or values. The spread operator ([...a, ...b]) is the modern equivalent.
.join(separator?)
Joins all elements into a string, separated by separator (default ","). The reverse of String.split().
.flat(depth?)
Flattens nested arrays by depth levels (default 1). Use Infinity to flatten fully regardless of depth.
.flatMap(fn)
Maps each element through a function, then flattens the result by one level. Equivalent to .map(fn).flat(1) but more efficient.
JavaScript — slice, concat, join, flat
const letters = ["a", "b", "c", "d", "e"]; 

// slice — extract portion 
letters.slice(1, 4);   // ["b","c","d"] 
letters.slice(2);      // ["c","d","e"] 
letters.slice(-2);     // ["d","e"]  — last 2 
letters.slice();      // shallow copy of entire array 

// concat — merge arrays 
const a = [1, 2], b = [3, 4]; 
a.concat(b, [5]);   // [1,2,3,4,5] 
[...a, ...b, 5];     // [1,2,3,4,5] — modern equivalent 

// join — array to string 
["2025", "01", "31"].join("-");  // "2025-01-31" 
["H", "e", "l", "l", "o"].join("");  // "Hello" 

// flat — flatten nested arrays 
[1, [2, 3], [4, [5]]].flat();     // [1,2,3,4,[5]]  — depth 1 
[1, [2, [3, [4]]]].flat(Infinity); // [1,2,3,4]   — fully flat 

// flatMap — map then flatten one level 
const sentences = ["Hello World", "Foo Bar"]; 
sentences.flatMap(s => s.split(" ")); 
// ["Hello","World","Foo","Bar"]
⚡
Free Resource
Download our JavaScript Cheat Sheet
All array methods, map/filter/reduce & patterns — on one page.
Get Sheet

Sorting & Reversing

sort() and reverse() mutate the original array. ES2023 adds toSorted() and toReversed() as pure equivalents that return a new array:

JavaScript — sort & reverse
// ❌ Default sort uses string comparison — wrong for numbers! 
[10, 2, 30, 4].sort();  // [10, 2, 30, 4] → "10" < "2" alphabetically! 

// ✅ Always provide a compare function for numbers 
[10, 2, 30, 4].sort((a, b) => a - b);  // [2, 4, 10, 30] ascending 
[10, 2, 30, 4].sort((a, b) => b - a);  // [30, 10, 4, 2] descending 

// Sort strings alphabetically (default is fine for plain strings) 
["banana", "apple", "cherry"].sort(); 
// ["apple", "banana", "cherry"] 

// Sort objects by property 
const people = [{name:"Zara",age:25},{name:"Ali",age:30},{name:"Priya",age:22}]; 
people.sort((a, b) => a.age - b.age); // by age ascending 
people.sort((a, b) => a.name.localeCompare(b.name)); // by name 

// reverse — reverses in place 
const arr = [1, 2, 3, 4, 5]; 
arr.reverse();  // [5,4,3,2,1] — arr is mutated! 

// ✅ ES2023 — pure non-mutating versions 
const nums = [3, 1, 4, 1, 5]; 
const sorted   = nums.toSorted((a, b) => a - b); // new array 
const reversed = nums.toReversed();               // new array 
console.log(nums);     // [3,1,4,1,5] — unchanged! 
console.log(sorted);   // [1,1,3,4,5] 
console.log(reversed); // [5,1,4,1,3]
Watch out
The default .sort() converts elements to strings before comparing. This makes 10 sort before 2 because "10" < "2" lexicographically. Always pass a comparator function when sorting numbers: (a, b) => a - b.

Full Method Quick Reference

Every essential array method at a glance — with mutation status, return value, and a one-line example:

Method Mutates? Returns Quick Example → Result
.push(x) Yes New length [1,2].push(3) → 3 (len)
.pop() Yes Removed element [1,2,3].pop() → 3
.unshift(x) Yes New length [2,3].unshift(1) → 3 (len)
.shift() Yes Removed element [1,2,3].shift() → 1
.splice(s,d,...) Yes Removed elements array [1,2,3].splice(1,1) → [2]
.sort(fn?) Yes Same array (sorted) [3,1,2].sort((a,b)=>a-b) → [1,2,3]
.reverse() Yes Same array (reversed) [1,2,3].reverse() → [3,2,1]
.fill(v, s?, e?) Yes Same array (filled) [1,2,3].fill(0,1) → [1,0,0]
.slice(s?,e?) No New array [1,2,3,4].slice(1,3) → [2,3]
.concat(...arrs) No New array [1].concat([2],[3]) → [1,2,3]
.indexOf(x) No Index or -1 [10,20].indexOf(20) → 1
.includes(x) No Boolean [1,2,3].includes(2) → true
.find(fn) No Element or undefined [1,5,8].find(x=>x>4) → 5
.findIndex(fn) No Index or -1 [1,5,8].findIndex(x=>x>4) → 1
.every(fn) No Boolean [2,4].every(x=>x%2===0) → true
.some(fn) No Boolean [1,3,4].some(x=>x%2===0) → true
.join(sep?) No String ["a","b"].join("-") → "a-b"
.flat(depth?) No New array [1,[2,[3]]].flat() → [1,2,[3]]
.flatMap(fn) No New array ["a b"].flatMap(s=>s.split(" ")) → ["a","b"]
.at(i)ES2022 No Element or undefined [1,2,3].at(-1) → 3
.toSorted(fn?)ES2023 No New sorted array [3,1].toSorted((a,b)=>a-b) → [1,3]
.toReversed()ES2023 No New reversed array [1,2,3].toReversed() → [3,2,1]
Array.isArray(v) No Boolean Array.isArray([1,2]) → true
Array.from(iter) No New array Array.from("abc") → ["a","b","c"]

Try It — Live Editor

Experiment with array methods below. Try changing the data, chaining methods, or testing the mutating vs pure difference.

Live Editor
✎ Editor
👁 Preview

Common Patterns & Recipes

These are the real-world array utilities you'll reach for constantly in JavaScript projects:

JavaScript — Array Method Recipes
// ── Remove duplicates ──────────────────────────────────────── const unique = [...new Set([1, 2, 2, 3, 3, 3])]; // [1,2,3] // ── Remove item by value (non-mutating) ─────────────────────── const arr = ["a", "b", "c"]; const without = arr.filter(x => x !== "b"); // ["a","c"] // ── Remove item by index (non-mutating) ─────────────────────── const removeAt = (arr, i) => [...arr.slice(0, i), ...arr.slice(i + 1)]; removeAt([1, 2, 3, 4], 2); // [1,2,4] // ── Update item in array (non-mutating) ─────────────────────── const updateAt = (arr, i, val) => arr.map((x, idx) => idx === i ? val : x); updateAt([1, 2, 3], 1, 99); // [1,99,3] // ── Chunk array into pages ──────────────────────────────────── function chunk(arr, size) { const result = []; for (let i = 0; i < arr.length; i += size) { result.push(arr.slice(i, i + size)); } return result; } chunk([1,2,3,4,5], 2); // [[1,2],[3,4],[5]] // ── Shuffle (Fisher-Yates) ──────────────────────────────────── function shuffle(arr) { const a = [...arr]; for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; } // ── Group array items by key ───────────────────────────────── const people = [{name:"Alice",role:"dev"},{name:"Bob",role:"design"},{name:"Carol",role:"dev"}]; const grouped = people.reduce((acc, p) => { (acc[p.role] ??= []).push(p.name); return acc; }, {}); // { dev: ["Alice","Carol"], design: ["Bob"] }
Quick Check
What does [1, 2, 3].indexOf(5) return?
Quick Check
Which method should you use to sort numbers correctly in JavaScript?
Chapter Summary
  • Array methods are either mutating (change the original: push, pop, splice, sort, reverse, fill) or pure (return new: slice, concat, flat, toSorted, toReversed).
  • push / pop add and remove from the end; unshift / shift add and remove from the start.
  • splice(start, deleteCount, ...items) can insert, remove, or replace elements at any position.
  • indexOf / includes find primitives; find / findIndex find objects using a callback predicate.
  • every checks if all elements pass; some checks if at least one passes.
  • sort() uses string comparison by default — always pass (a, b) => a - b for numbers.
  • ES2023 adds toSorted(), toReversed(), toSpliced() — non-mutating versions of the classic methods.
  • flat(depth) flattens nested arrays; flatMap(fn) maps and flattens in one pass.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel