Script Valley
JavaScript: The Complete Language
Objects, Arrays, and DestructuringLesson 3.2

Arrays: methods every JavaScript developer must know

push pop shift unshift, splice slice, indexOf includes find findIndex, sort, flat flatMap, Array.from Array.isArray, forEach vs map differences, mutation vs immutability

Arrays Are Ordered Lists

Arrays are objects with integer keys and a length property. The single most important thing to know about array methods: some mutate the original, some return a new array. Mixing them up silently corrupts data.

Mutating Methods — Change the Original

const arr = [1, 2, 3];
arr.push(4);          // [1,2,3,4] — adds to end
arr.pop();            // [1,2,3]   — removes from end
arr.unshift(0);       // [0,1,2,3] — adds to start
arr.shift();          // [1,2,3]   — removes from start
arr.splice(1, 1, 99); // [1,99,3]  — remove and optionally insert
arr.sort((a,b) => a - b); // sorts in place
arr.reverse();        // reverses in place

Non-Mutating Methods — Return New Value

const nums = [3, 1, 4, 1, 5];
nums.slice(1, 3)              // [1, 4] — does not modify nums
nums.concat([9, 10])          // [3,1,4,1,5,9,10]
[[1],[2],[3]].flat()          // [1, 2, 3]

Search Methods

nums.indexOf(4)           // 2
nums.includes(5)          // true
nums.find(n => n > 3)     // 4 — first match value
nums.findIndex(n => n > 3)// 2 — first match index
nums.every(n => n > 0)    // true
nums.some(n => n > 4)     // true

Utilities

Array.from("hi")          // ["h","i"]
Array.isArray([])         // true

Up next

Destructuring arrays and objects in JavaScript

Sign in to track progress