Study notes · 9% of the exam

Arrays, Collections and Immutability

Know which array methods mutate and which copy, how holes, sorting and reduce behave at the edges, and when a Map, Set or weak collection beats a plain object or array.

Key points

  1. 1

    Mutators: push, pop, shift, unshift, splice, sort, reverse, fill, copyWithin. Copying versions (ES2023): toSorted, toReversed, toSpliced, with.

  2. 2

    sort() compares strings by default, so pass (a, b) => a - b for numbers. Comparators must return negative, zero or positive consistently. Sort is stable since ES2019.

  3. 3

    Always give reduce an initial value: it avoids the empty-array TypeError and the single-element shortcut.

  4. 4

    Destructuring defaults apply only to undefined. Object rest and spread copy own enumerable properties into a new plain object and are shallow.

  5. 5

    Map keeps key types and pure insertion order and has size. Set dedupes with SameValueZero (NaN equals NaN, -0 becomes +0). ES2025 adds union, intersection and friends.

  6. 6

    WeakMap and WeakSet hold object (or non-registered symbol) keys weakly and can't be iterated. WeakRef and FinalizationRegistry give no timing guarantees.

  7. 7

    Array-likes have length; iterables have Symbol.iterator. Array.from accepts both, spread only iterables.

Common traps

  • ['1', '2', '3'].map(parseInt) is [1, NaN, NaN] because map passes the index as the radix.

  • Holes: forEach, map, filter and indexOf skip them; for...of, Array.from, includes and toSorted read them as undefined.

  • Object.groupBy returns a null-prototype object, not a Map, so result.hasOwnProperty is undefined.

Test yourself on Arrays, Collections and Immutability

Ten questions, with the answer and explanation after each one.