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
