Arrays — reference
The full picture of arrays in JavaScript. Use this once you have built something with them.
A complete mental model of arrays as JavaScript implements them, with examples for each method.
Prerequisites
You have used arrays at least once. A reference is most useful after you have already needed it.
A reference is most useful once you have already needed it. If you have never written array.map, stop here and go build something. Come back when you find yourself reaching for a method and want the full menu.
The mental model
A JavaScript array is an ordered list. It is integer-indexed starting from 0. It can hold values of any type, in any combination. It is mutable. Its length is dynamic.
const xs = [1, 'two', { three: 3 }, [4]];xs.length; // 4xs[0]; // 1xs[3]; // [4]Mutation
- arr.push(x)
- Append x. Returns the new length.
- arr.pop()
- Remove and return the last element.
- arr.unshift(x)
- Prepend x. Slow on large arrays.
- arr.shift()
- Remove and return the first element. Also slow.
- arr.splice(i, n, ...x)
- Remove n items at index i, optionally insert x. Mutates.
- arr.sort(fn)
- In-place sort. Default compares as strings — pass a comparator for numbers.
Iteration that returns a new array
These do not mutate the original. They return a new array.
xs.map(x => x * 2); // [2, 4, 6]xs.filter(x => x > 1); // [2, 3]xs.flatMap(x => [x, x]); // [1, 1, 2, 2, 3, 3]xs.slice(1); // [2, 3]Aggregations
xs.reduce((acc, x) => acc + x, 0); // sumxs.some(x => x > 2); // truexs.every(x => x > 0); // truexs.find(x => x > 1); // 2xs.includes(2); // trueMore like this
CSS card — reference
One-liner reference for the card project’s properties — scan, copy, and open the live example.
CSS card — cheatsheet
The box-model card at a glance — the handful of properties that do the work, ready to copy.
Build your first web page
Hand-write a small, semantic page — a heading, a paragraph, a list — then open the same project in /code and make it yours.
Liked this one?
Pass it on
Discussion
Be the first to ask
Your questions stay private with the author. The author can pin answers to share with everyone.
Sign in to ask a question privately on this tutorial.
Sign inNo pinned answers yet for this tutorial.