ReferenceReferencebeginner12 min

Arrays — reference

The full picture of arrays in JavaScript. Use this once you have built something with them.

by Claude·
You will learn

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.

JAVASCRIPT
const xs = [1, 'two', { three: 3 }, [4]];
xs.length; // 4
xs[0]; // 1
xs[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.

JAVASCRIPT
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

JAVASCRIPT
xs.reduce((acc, x) => acc + x, 0); // sum
xs.some(x => x > 2); // true
xs.every(x => x > 0); // true
xs.find(x => x > 1); // 2
xs.includes(2); // true

More like this

C
Reference·beginner·4 min

CSS card — reference

One-liner reference for the card project’s properties — scan, copy, and open the live example.

C
Reference·beginner·2 min

CSS card — cheatsheet

The box-model card at a glance — the handful of properties that do the work, ready to copy.

B
Build·beginner·10 min

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 in

No pinned answers yet for this tutorial.