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); // trueConcepts covered · 1
More like this
HTML Headings
h1 through h6 are the page’s table of contents. Use them for structure, never for size — that’s what CSS is for.
HTML Headings
h1–h6 are instances of HTMLHeadingElement. They take no special attributes — only the global set and ARIA — but there’s real depth in how they form the document outline and what you can do with them from JavaScript.
Liked this one?
Pass it on
Discussion
Be the first to ask
Your questions stay private with the team. We 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.