JavaScriptEasy
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 (unlikenew 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 copiestoSorted,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"; useArray.isArray.- Arrays can have holes (
[1, , 3]), which some methods skip. - Setting
lengthtruncates the array. - Arrays are compared by reference, so
[1] === [1]isfalse.
Code example
js
1const scores = [72, 95, 88, 60];23console.log(scores.length, scores[0], scores.at(-1)); // 4 72 6045// 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 unchanged910// Transform, filter, aggregate11const 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.751415// Search16console.log(scores.find((s) => s > 90), scores.findLast((s) => s > 70), scores.includes(60));1718// Create arrays19console.log(Array.from({ length: 5 }, (_, i) => i * i)); // [0, 1, 4, 9, 16]20console.log(Array.from(new Set("banana"))); // ["b", "a", "n"]2122// Group (ES2024)23console.log(Object.groupBy(scores, (s) => (s >= 70 ? "pass" : "fail")));2425console.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.