What is an array?

An array is an ordered, zero-indexed list of values of any type; in JavaScript it is a special object whose keys are indexes and whose length updates automatically.

Creating arrays

  • Literal: [1, 2, 3].
  • Array.from(iterable, mapFn): from a Set, string, NodeList, or { length: n }.
  • Array.of(7): a single-element array (unlike new Array(7), which makes 7 empty slots).
  • new Array(n).fill(0): pre-filled array.

Mutating vs non-mutating methods

  • Mutate: push, pop, shift, unshift, splice, sort, reverse, fill.
  • Return new arrays: map, filter, slice, concat, flat, and the ES2023 copies toSorted, toReversed, toSpliced, with(index, value). These are ideal for React state.
  • Search: find, findIndex, findLast, findLastIndex, includes, indexOf, some, every.
  • Access: at(-1) reads from the end.
  • Group: Object.groupBy(array, fn) (ES2024).

Things to know

  • typeof [] === "object"; use Array.isArray.
  • Arrays can have holes ([1, , 3]), which some methods skip.
  • Setting length truncates the array.
  • Arrays are compared by reference, so [1] === [1] is false.

Code example

js
1const scores = [72, 95, 88, 60];
2
3console.log(scores.length, scores[0], scores.at(-1)); // 4 72 60
4
5// Non-mutating (good for state updates)
6const sorted = scores.toSorted((a, b) => b - a);
7const updated = scores.with(1, 100);
8console.log(sorted, updated, scores); // original unchanged
9
10// Transform, filter, aggregate
11const passed = scores.filter((s) => s >= 70).map((s) => `${s}%`);
12const average = scores.reduce((sum, s) => sum + s, 0) / scores.length;
13console.log(passed, average); // ["72%", "95%", "88%"] 78.75
14
15// Search
16console.log(scores.find((s) => s > 90), scores.findLast((s) => s > 70), scores.includes(60));
17
18// Create arrays
19console.log(Array.from({ length: 5 }, (_, i) => i * i)); // [0, 1, 4, 9, 16]
20console.log(Array.from(new Set("banana"))); // ["b", "a", "n"]
21
22// Group (ES2024)
23console.log(Object.groupBy(scores, (s) => (s >= 70 ? "pass" : "fail")));
24
25console.log(Array.isArray(scores), typeof scores); // true "object"

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app