# Array and String Method Cheat Sheet

Course: [JavaScript](https://www.devtutorials.ai/learn/javascript) · Section: Reference
Source: https://www.devtutorials.ai/learn/javascript/reference/method-cheat-sheet

> Every array and string method this course uses, with what it returns, whether it mutates, and a Try button on every row to run it for real.

Every array and string method this course uses, in one place.

- Each row has a **▶ Try** button. Press it, and a runner opens with real code; edit it and Run again.
- **Arrays:** watch the **Mutates** column. Nine methods change the array itself; four have copying twins (`toSorted`, `toReversed`, `toSpliced`, `with`).
- **Strings:** a string is **immutable**. Every method returns a new string, so forgetting to use the return value is the most common string bug.

## Array methods

```js runnable title="The whole table, run against the practice data"
const skus = products.slice(0, 5).map((p) => p.sku);

console.log("map:      ", skus.map((s) => s.slice(0, 2)));
console.log("filter:   ", skus.filter((s) => s.startsWith("M")));
console.log("reduce:   ", skus.reduce((n, s) => n + s.length, 0));
console.log("flatMap:  ", orders.slice(0, 2).flatMap((o) => o.items).length, "line items from 2 orders");
console.log("find:     ", orders.find((o) => o.status === "refunded").id);
console.log("some/every:", orders.some((o) => o.items.length === 0), orders.every((o) => o.currency === "USD"));
console.log("at(-1):   ", skus.at(-1));
console.log("toSorted: ", [10, 9, 1, 20].toSorted((a, b) => a - b));
console.log("sort():   ", [10, 9, 1, 20].sort(), "← text order");
console.log("with:     ", skus.with(0, "REPLACED").slice(0, 2));
console.log("groupBy:  ", Object.keys(Object.groupBy(orders, (o) => o.status)));
```

## The mutation trap, in one cell

```js runnable title="Nine mutating methods, and what each leaves behind"
const show = (label, build) => {
  const arr = [3, 1, 2];
  const returned = build(arr);
  console.log(label.padEnd(12), "returned:", JSON.stringify(returned).padEnd(14), "array is now:", JSON.stringify(arr));
};

show("push", (a) => a.push(4));
show("pop", (a) => a.pop());
show("unshift", (a) => a.unshift(0));
show("shift", (a) => a.shift());
show("splice", (a) => a.splice(1, 1));
show("sort", (a) => a.sort((x, y) => x - y));
show("reverse", (a) => a.reverse());
show("fill", (a) => a.fill(9));
show("toSorted", (a) => a.toSorted((x, y) => x - y));
show("toReversed", (a) => a.toReversed());
show("with", (a) => a.with(0, 99));
```

The last three left the array alone. The first eight did not — and `sort`, `reverse` and `fill` all return
the array too, so a chain reads exactly like a non-mutating one.

## Choosing between the similar array methods

| You want | Use | Not |
|---|---|---|
| the first matching element | `find` | `filter(…)[0]` — visits everything |
| whether anything matches | `some` | `filter(…).length > 0` |
| whether a value is present | `includes` | `indexOf(x) !== -1` |
| one value per element | `map` | `forEach` plus `push` |
| fewer elements | `filter` | `map` returning `undefined` |
| one row per nested item | `flatMap` | `map` then `flat` |
| a total | `reduce(fn, 0)` | `reduce(fn)` — throws on an empty array |
| an index alongside the value | `entries()` | a manual counter |
| a sorted copy | `toSorted` | `sort` on data you were given |
| to stop as soon as you know | `find` / `some` / a loop with `break` | `map` or `filter` |

## Array gotchas worth re-reading

| | |
|---|---|
| `sort()` with no comparator | compares as strings: `[1, 10, 20, 9]` |
| a comparator returning a boolean | must return a negative number, positive number or `0` |
| `[].every(fn)` | `true` — there is no element that fails |
| `[].reduce(fn)` with no initial value | throws `Reduce of empty array with no initial value` |
| `arr[-1]` | `undefined` — use `at(-1)` |
| `new Array(3)` | three holes; `map` and `filter` skip them, `for...of` does not |
| `delete arr[1]` | leaves a hole and does not change `length` |
| `typeof []` | `"object"` — use `Array.isArray` |
| `[...arr]` on an array of objects | copies the array, shares the objects |
| `forEach` with an `async` callback | does not wait |
| `map` callback with braces and no `return` | an array of `undefined` |
| `NodeList.map` | does not exist — spread it first |

```js runnable title="Every array gotcha in the table above, demonstrated"
console.log("sort() as text:      ", [1, 10, 20, 9].sort());
console.log("boolean comparator:  ", [24, 180, 12, 60].toSorted((a, b) => a > b));
console.log("[].every:            ", [].every((n) => n > 100));
console.log("arr[-1] vs at(-1):   ", [1, 2, 3][-1], [1, 2, 3].at(-1));
console.log("new Array(3):        ", new Array(3), "| length", new Array(3).length);
console.log("holes and map:       ", (() => { const a = [1, 2, 3]; delete a[1]; return [a.length, a.map((x) => x)]; })());
console.log("typeof / isArray:    ", typeof [], Array.isArray([]));
console.log("map with no return:  ", [1, 2].map((n) => { n * 2; }));
console.log("reduce with no init: ", (() => { try { return [].reduce((a, b) => a + b); } catch (e) { return e.message; } })());
```

## Array performance, only where it matters

| | |
|---|---|
| `push`/`pop` | fast — work at the end |
| `shift`/`unshift` | move every other element; avoid in a hot loop over a large array |
| `includes`/`indexOf`/`find` | scan from the start — build a `Set` or `Map` if you look up repeatedly |
| `find` inside a loop over another array | that is a nested scan; build a lookup `Map` once |
| `sort` | required to be stable, so sorting by one field then another sorts by both |
| chaining `filter` before `map` | transforms fewer elements than the other order |

```js runnable title="A repeated find, and the Map that replaces it"
let scans = 0;
let lookups = 0;

const bySku = new Map(products.map((p) => [p.sku, p]));

for (const item of orders.flatMap((o) => o.items)) {
  products.find((p) => { scans += 1; return p.sku === item.sku; });
  bySku.get(item.sku);
  lookups += 1;
}

console.log("line items:", lookups);
console.log("comparisons with find:", scans);
console.log("direct Map lookups:   ", lookups);
```

## String methods

```js runnable title="The searching and extracting tables, run"
const email = customers[0].email;
const sku = products[0].sku;

console.log("email:            ", email);
console.log("includes('@'):    ", email.includes("@"));
console.log("startsWith:       ", email.startsWith("priya"));
console.log("indexOf('@'):     ", email.indexOf("@"));
console.log("slice to the @:   ", email.slice(0, email.indexOf("@")));
console.log("slice from the @: ", email.slice(email.indexOf("@") + 1));
console.log("slice(-8):        ", email.slice(-8));
console.log("at(-1) / [0]:     ", sku.at(-1), sku[0]);
console.log("charAt past end:  ", JSON.stringify(sku.charAt(99)), "| [99]:", sku[99]);
console.log("slice backwards:  ", JSON.stringify(sku.slice(4, 1)), "| substring:", JSON.stringify(sku.substring(4, 1)));
```

```js runnable title="The changing and splitting tables, run"
const city = customers[11].city;

console.log("raw:              ", JSON.stringify(city));
console.log("trim:             ", JSON.stringify(city.trim()));
console.log("original intact:  ", JSON.stringify(city));
console.log("collapse spaces:  ", JSON.stringify("  a   b  ".trim().split(/\s+/).join(" ")));
console.log("padStart:         ", JSON.stringify(String(7).padStart(4, "0")));
console.log("padStart too long:", JSON.stringify("already".padStart(3, "-")));
console.log("repeat:           ", "-".repeat(12));
console.log("replace:          ", "/a/b/a".replace("a", "z"));
console.log("replaceAll:       ", "/a/b/a".replaceAll("a", "z"));
console.log("split('/'):       ", "/a/b".split("/"));
console.log("split('') vs spread:", "cafe\u0301".split("").length, [..."cafe\u0301"].length);
```

`"total: " + someObject` gives `"total: [object Object]"`. Seeing that string in output means something
asked an object to become text — name the field you wanted, or `JSON.stringify` it.

## Comparing strings

```js runnable title="Five comparisons of the same two values"
const a = customers[3].email;
const b = customers[6].email;

console.log("a:", a);
console.log("b:", b);
console.log("===:                ", a === b);
console.log("lower-cased:        ", a.toLowerCase() === b.toLowerCase());
console.log("sensitivity base:   ", a.localeCompare(b, undefined, { sensitivity: "base" }) === 0);
console.log("default sort:       ", ["Zebra", "apple", "Ápple"].toSorted());
console.log("localeCompare sort: ", ["Zebra", "apple", "Ápple"].toSorted((x, y) => x.localeCompare(y)));
console.log("numeric sort:       ", ["file10", "file2", "file1"].toSorted((x, y) => x.localeCompare(y, undefined, { numeric: true })));
```

## Formatting numbers and dates into strings

```js runnable title="Formatting, and the string that is no longer a number"
const total = 27857.469999999998;

console.log("toFixed(2):       ", total.toFixed(2), "| type:", typeof total.toFixed(2));
console.log("toFixed then + 1: ", total.toFixed(2) + 1, "← concatenated");
console.log("Number() first:   ", Number(total.toFixed(2)) + 1);
console.log("as currency:      ", new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(total));
console.log("as a percentage:  ", new Intl.NumberFormat("en-US", { style: "percent" }).format(0.0731));
console.log("grouped:          ", new Intl.NumberFormat("en-US").format(1234567.891));
```

## Escapes

```js runnable title="Every escape, printed"
console.log("newline:\nsecond line");
console.log("tab:\tafter");
console.log("backslash:", "C:\\Users\\Priya");
console.log("quotes:", "she said \"yes\"", 'and \'no\'');
console.log("unicode:", "\u00e9", "\u{1F600}");
console.log("dollar in a template:", `\${not interpolated}`);
```

## Length is code units, not characters

```js runnable title="Four strings, four surprising lengths"
for (const value of ["Nairobi", "café", "cafe\u0301", "👍", "🇰🇪"]) {
  console.log(
    JSON.stringify(value).padEnd(14),
    "length:", String(value.length).padEnd(3),
    "spread:", String([...value].length).padEnd(3),
    "segments:", [...new Intl.Segmenter().segment(value)].length,
  );
}
```

`length` counts UTF-16 code units. `[...str]` counts code points. `Intl.Segmenter` counts what a person
would call a character — which is the only one of the three that gets a flag or a combining accent right.

## String gotchas

| | |
|---|---|
| calling `trim()` without keeping the result | strings are immutable; nothing changes |
| `replace` with a string argument | first occurrence only |
| `replaceAll` with a non-global regex | throws |
| `substring` with backwards arguments | silently swaps them; `slice` returns `""` |
| `str[-1]` | `undefined` — use `at(-1)` |
| `charAt` past the end | `""`, not `undefined` |
| `"total: " + obj` | `"total: [object Object]"` |
| a real newline inside `'…'` | syntax error — use a backtick |
| `split("")` on emoji | splits inside the character |
| `toFixed` output | a string, so `+` concatenates |
| comparing user text with `===` | case and whitespace both matter |

```js runnable title="The string gotchas, demonstrated"
let city = "  Nairobi  ";
city.trim();
console.log("trim not kept:     ", JSON.stringify(city));
city = city.trim();
console.log("trim assigned:     ", JSON.stringify(city));
console.log("replace vs All:    ", "/a/b/a".replace("a", "z"), "|", "/a/b/a".replaceAll("a", "z"));
console.log("replaceAll no g:   ", (() => { try { return "/a/a".replaceAll(/a/, "z"); } catch (e) { return e.constructor.name + ": " + e.message.slice(0, 40); } })());
console.log("substring swaps:   ", JSON.stringify("KB-1180".substring(4, 1)), "| slice:", JSON.stringify("KB-1180".slice(4, 1)));
console.log("object as text:    ", "total: " + { seats: 24 });
console.log("array as text:     ", "tags: " + ["team", "global"]);
```

## Related pages

- [Array Fundamentals](/learn/javascript/arrays/array-fundamentals) — creating, reading, adding, removing, copying and combining arrays
- [Array Operations](/learn/javascript/arrays/array-operations) — map, filter, reduce, find, some, every, sorting and grouping
- [Data Types](/learn/javascript/basics/data-types) — strings, numbers and converting between types
- [Date Formatting and Time Zones](/learn/javascript/dates/date-formatting-and-time-zones) — `Intl.DateTimeFormat`

You have reached the end of the JavaScript course. Come back to this page whenever you need a method.
