Arrays in JavaScript
Arrays are ordered, mutable collections with zero‑based indexing.
Creating arrays
const empty = []
const nums = [1,2,3]
const fromCtor = Array(3).fill(0)
const ofVals = Array.of(1,2,3)
Indexing and length
nums[0] // 1
nums[nums.length - 1]
Adding/removing
const xs = [1,2]
xs.push(3) // add to end
xs.pop() // remove last
xs.unshift(0) // add to start
xs.shift() // remove first
Transform and query
Non‑mutating vs mutating methods; prefer non‑mutating when possible.
[1,2,3].map(n => n * 2) // [2,4,6]
[1,2,3,4].filter(n => n % 2 === 0)
[1,2,3].reduce((a,b) => a+b, 0)
[1,2,2,3].includes(2)
Slicing and splicing
const a = [10,20,30,40]
a.slice(1, 3) // [20,30] (non‑mutating)
a.splice(1, 2, 99) // mutates a
Copy and spread
const copy = [...a]
const merged = [...a, ...[50,60]]
Sorting and comparing
sort mutates and compares as strings by default; supply a comparator for numeric sorts.
[3,10,2].sort((a,b) => a-b)
Iteration
Prefer for..of or array methods; avoid for..in for arrays.
for (const v of nums) {}
nums.forEach(v => {})
Flat and flatMap
[[1,2],[3]].flat() // [1,2,3]
[1,2,3].flatMap(n => [n, n+10])
Performance notes
- Push/pop are fast; shift/unshift are O(n)
- Avoid creating large holes (sparse arrays) unless needed
Summary
- Use non‑mutating methods for clarity; know when
splice/sortmutate - Spread, slice, and
flatsimplify copies and reshaping