# 4 JavaScript Array Bugs Beginners Hit — and How to Watch Them Happen

Array bugs rarely crash. The function runs, a list comes back, and it is *almost* right: one item is `NaN`, one zero survived, `100` landed in front of `9`.

That "almost" is the clue. Each bug in this post hides in something you can't see by reading the code top to bottom: whether a variable holds a **position** or an **item**, what a search result really means, how the list changes underneath your loop, and which rule `sort` uses when you don't give it one. Watch the values change one step at a time and the bug points at itself.

Each bug below has:

1. a short snippet with the bug,
2. a **Predict before running** prompt (do it on paper, it takes a minute),
3. what the step-by-step trace actually shows,
4. a lab: the broken function, opened in a step-through visualizer, where you fix it and get checked against hidden cases,
5. the fix, written out under the lab so you can try first.

The labs use [Code Glyphs](https://iineman2.github.io/code-glyphs/), a browser step-through tool I built. You don't need it to follow along: every snippet is plain JavaScript you can paste into Node or the browser console.

**How the labs work.** Each lab opens with the broken function already loaded. Press **Step** to advance one stroke at a time and watch the values change, or **Run** to go straight to the result. Edit the shape (or the JavaScript pane), then press **Check my shape**. It runs your fix on the cases shown and on some hidden ones. Opening a lab link never runs anything until you press a button. A small vocabulary note: Code Glyphs calls variables "wells", loops "rings" and conditions "gates". It shows `undefined` as **nothing**, and `true` / `false` as **yes** / **no**.

If the embedded labs don't load where you're reading this, every lab also has a plain link right under it.

---

## Bug 1: `for...of` hands you the item, not its index

```js
function doubled(nums) {
  const out = [];
  for (const n of nums) {
    out.push(nums[n] * 2);
  }
  return out;
}

doubled([3, 1, 2]);
```

**Predict before running.** Write down `n` for each turn of the loop, and what gets pushed. What list comes back?

**What happens.** `[NaN, 2, 4]`. Expected: `[6, 2, 4]`. Two out of three are right, which makes it look like an arithmetic problem. It isn't one.

**What the trace shows.** Step through `doubled([3, 1, 2])` and watch the well for `n`:

| Turn | `n` | `nums[n]` | Pushed |
| --- | --- | --- | --- |
| 1 | `3` | `nums[3]`: **nothing** (there is no index 3) | `NaN` |
| 2 | `1` | `nums[1]`: `1` | `2` |
| 3 | `2` | `nums[2]`: `2` | `4` |

`n` is never `0`. It takes the *items* `3`, `1`, `2`, and then the code uses each item as a *position*. The list only has positions 0, 1 and 2, so `nums[3]` reads **nothing** (`undefined`), and `undefined * 2` is `NaN`. The other two turns are right by luck: in this list, the items `1` and `2` happen to sit at positions 1 and 2. Give it `[10, 20, 30, 40]` and every read misses: `[NaN, NaN, NaN, NaN]`.

**The mental model.** There are two ways to walk a list, and each one gives you a different thing:

| Loop | The loop variable is | To get the item |
| --- | --- | --- |
| `for (const n of nums)` | the item | `n` |
| `for (let i = 0; i < nums.length; i++)` | the position | `nums[i]` |

`nums[n]` mixes the two. A naming habit helps: `i` only ever holds a position, and an item gets a real name (`n`, `score`, `tag`). Then `nums[score]` looks wrong the moment you type it. (And skip `for...in` on arrays. It gives you the positions as *strings*: `"0"`, `"1"`, `"2"`.)

**Lab: fix `doubled`.** Case 1 is the list you just traced.

<iframe src="https://iineman2.github.io/code-glyphs/?embed=1#e=eyJ2IjoxLCJrIjoiZml4IiwidCI6IkRvdWJsZSBldmVyeSBpdGVtIiwicCI6Im51bXMgaXMgYSBsaXN0IG9mIHdob2xlIG51bWJlcnMuIEZpeCB0aGUgc2hhcGUgc28gaXQgbGVhdmVzIHdpdGggYSBuZXcgbGlzdCBob2xkaW5nIGVhY2ggbnVtYmVyIGRvdWJsZWQsIGluIHRoZSBzYW1lIG9yZGVyLiBGb3IgbnVtcyA9IFszLCAxLCAyXSB0aGF0IGlzIFs2LCAyLCA0XS4iLCJmbiI6ImRvdWJsZWQiLCJhIjpbIm51bXMiXSwicyI6ImZ1bmN0aW9uIGRvdWJsZWQobnVtcykge1xuICBjb25zdCBvdXQgPSBbXTtcbiAgZm9yIChjb25zdCBuIG9mIG51bXMpIHtcbiAgICBvdXQucHVzaChudW1zW25dICogMik7XG4gIH1cbiAgcmV0dXJuIG91dDtcbn1cbiIsImMiOltbIlszLCAxLCAyXSJdLFsiW10iXV0sImgiOltbIls1XSJdLFsiWzAsIDRdIl0sWyJbLTIsIDcsIDFdIl0sWyJbMTAsIDIwLCAzMCwgNDBdIl1dLCJ3IjpbIls2LCAyLCA0XSIsIltdIiwiWzEwXSIsIlswLCA4XSIsIlstNCwgMTQsIDJdIiwiWzIwLCA0MCwgNjAsIDgwXSJdLCJwYXIiOnsicCI6MTMsInMiOjEyN319" width="100%" height="680" style="border:0;max-width:100%" allow="clipboard-write" loading="lazy" title="Code Glyphs puzzle: Double every item"></iframe>

[Open this lab in a new tab](https://iineman2.github.io/code-glyphs/#e=eyJ2IjoxLCJrIjoiZml4IiwidCI6IkRvdWJsZSBldmVyeSBpdGVtIiwicCI6Im51bXMgaXMgYSBsaXN0IG9mIHdob2xlIG51bWJlcnMuIEZpeCB0aGUgc2hhcGUgc28gaXQgbGVhdmVzIHdpdGggYSBuZXcgbGlzdCBob2xkaW5nIGVhY2ggbnVtYmVyIGRvdWJsZWQsIGluIHRoZSBzYW1lIG9yZGVyLiBGb3IgbnVtcyA9IFszLCAxLCAyXSB0aGF0IGlzIFs2LCAyLCA0XS4iLCJmbiI6ImRvdWJsZWQiLCJhIjpbIm51bXMiXSwicyI6ImZ1bmN0aW9uIGRvdWJsZWQobnVtcykge1xuICBjb25zdCBvdXQgPSBbXTtcbiAgZm9yIChjb25zdCBuIG9mIG51bXMpIHtcbiAgICBvdXQucHVzaChudW1zW25dICogMik7XG4gIH1cbiAgcmV0dXJuIG91dDtcbn1cbiIsImMiOltbIlszLCAxLCAyXSJdLFsiW10iXV0sImgiOltbIls1XSJdLFsiWzAsIDRdIl0sWyJbLTIsIDcsIDFdIl0sWyJbMTAsIDIwLCAzMCwgNDBdIl1dLCJ3IjpbIls2LCAyLCA0XSIsIltdIiwiWzEwXSIsIlswLCA4XSIsIlstNCwgMTQsIDJdIiwiWzIwLCA0MCwgNjAsIDgwXSJdLCJwYXIiOnsicCI6MTMsInMiOjEyN319)

**The fix.** `n` is already the item, so use it directly:

```js
function doubled(nums) {
  const out = [];
  for (const n of nums) {
    out.push(n * 2);
  }
  return out;
}
```

`doubled([3, 1, 2])` now gives `[6, 2, 4]`. (An index loop with `out.push(nums[i] * 2)` gives the same result. Pick one style and don't mix them.)

---

## Bug 2: `indexOf` finds it at position 0, and `if` hears "no"

```js
function hasTag(tags, tag) {
  if (tags.indexOf(tag)) {
    return true;
  }
  return false;
}

hasTag(["js", "css"], "js");
```

**Predict before running.** What does it return for `"js"`? For `"html"`? For `"css"`?

**What happens.**

| Call | Returns | Should be |
| --- | --- | --- |
| `hasTag(["js", "css"], "js")` | `false` | `true` |
| `hasTag(["js", "css"], "html")` | `true` | `false` |
| `hasTag(["js", "css"], "css")` | `true` | `true` |

It is wrong in *both* directions, and the one call that comes out right does so by accident.

**What the trace shows.** Step through `hasTag(["js", "css"], "js")` up to the `if`. Its condition, `tags.indexOf(tag)`, gives `0`, because `"js"` is the first item. `0` is falsy, so the gate answers **no**, and the run leaves through `return false` (the result panel says **no**). Now run it with `"html"`: `indexOf` gives `-1`, which means "not found", but `-1` is truthy, so the gate answers **yes**.

**The mental model.** `indexOf` doesn't answer a yes/no question. It answers "*where* is it?", and two of its answers break truthiness:

- `0` means "found, at the very front", and `0` is falsy.
- `-1` means "not found anywhere", and `-1` is truthy.

So never hand a position straight to `if`. Compare it explicitly with `!== -1`, or ask the yes/no question directly with `includes`, which returns `true` or `false`. The same goes for `findIndex`, which also answers `-1` when nothing matches.

**Lab: fix `hasTag`.** The hidden cases include an empty list and a tag at the very front.

<iframe src="https://iineman2.github.io/code-glyphs/?embed=1#e=eyJ2IjoxLCJrIjoiZml4IiwidCI6IklzIHRoZSB0YWcgaW4gdGhlIGxpc3Q_IiwicCI6InRhZ3MgaXMgYSBsaXN0IG9mIHdvcmRzIGFuZCB0YWcgaXMgb25lIHdvcmQuIEZpeCB0aGUgc2hhcGUgc28gaXQgbGVhdmVzIHdpdGggdHJ1ZSB3aGVuIHRhZyBpcyBzb21ld2hlcmUgaW4gdGFncywgYW5kIGZhbHNlIHdoZW4gaXQgaXMgbm90LiBGb3IgdGFncyA9IFtcImpzXCIsIFwiY3NzXCJdIGFuZCB0YWcgPSBcImpzXCIgdGhhdCBpcyB0cnVlLiIsImZuIjoiaGFzVGFnIiwiYSI6WyJ0YWdzIiwidGFnIl0sInMiOiJmdW5jdGlvbiBoYXNUYWcodGFncywgdGFnKSB7XG4gIGlmICh0YWdzLmluZGV4T2YodGFnKSkge1xuICAgIHJldHVybiB0cnVlO1xuICB9XG4gIHJldHVybiBmYWxzZTtcbn1cbiIsImMiOltbIltcImpzXCIsIFwiY3NzXCJdIiwiXCJqc1wiIl0sWyJbXCJqc1wiLCBcImNzc1wiXSIsIlwiaHRtbFwiIl1dLCJoIjpbWyJbXSIsIlwianNcIiJdLFsiW1wiYVwiLCBcImJcIiwgXCJjXCJdIiwiXCJjXCIiXSxbIltcImFcIiwgXCJiXCIsIFwiY1wiXSIsIlwiYVwiIl0sWyJbXCJ4XCJdIiwiXCJ5XCIiXSxbIltcInhcIl0iLCJcInhcIiJdXSwidyI6WyJ0cnVlIiwiZmFsc2UiLCJmYWxzZSIsInRydWUiLCJ0cnVlIiwiZmFsc2UiLCJ0cnVlIl0sInBhciI6eyJwIjoxMiwicyI6NjN9fQ" width="100%" height="680" style="border:0;max-width:100%" allow="clipboard-write" loading="lazy" title="Code Glyphs puzzle: Is the tag in the list?"></iframe>

[Open this lab in a new tab](https://iineman2.github.io/code-glyphs/#e=eyJ2IjoxLCJrIjoiZml4IiwidCI6IklzIHRoZSB0YWcgaW4gdGhlIGxpc3Q_IiwicCI6InRhZ3MgaXMgYSBsaXN0IG9mIHdvcmRzIGFuZCB0YWcgaXMgb25lIHdvcmQuIEZpeCB0aGUgc2hhcGUgc28gaXQgbGVhdmVzIHdpdGggdHJ1ZSB3aGVuIHRhZyBpcyBzb21ld2hlcmUgaW4gdGFncywgYW5kIGZhbHNlIHdoZW4gaXQgaXMgbm90LiBGb3IgdGFncyA9IFtcImpzXCIsIFwiY3NzXCJdIGFuZCB0YWcgPSBcImpzXCIgdGhhdCBpcyB0cnVlLiIsImZuIjoiaGFzVGFnIiwiYSI6WyJ0YWdzIiwidGFnIl0sInMiOiJmdW5jdGlvbiBoYXNUYWcodGFncywgdGFnKSB7XG4gIGlmICh0YWdzLmluZGV4T2YodGFnKSkge1xuICAgIHJldHVybiB0cnVlO1xuICB9XG4gIHJldHVybiBmYWxzZTtcbn1cbiIsImMiOltbIltcImpzXCIsIFwiY3NzXCJdIiwiXCJqc1wiIl0sWyJbXCJqc1wiLCBcImNzc1wiXSIsIlwiaHRtbFwiIl1dLCJoIjpbWyJbXSIsIlwianNcIiJdLFsiW1wiYVwiLCBcImJcIiwgXCJjXCJdIiwiXCJjXCIiXSxbIltcImFcIiwgXCJiXCIsIFwiY1wiXSIsIlwiYVwiIl0sWyJbXCJ4XCJdIiwiXCJ5XCIiXSxbIltcInhcIl0iLCJcInhcIiJdXSwidyI6WyJ0cnVlIiwiZmFsc2UiLCJmYWxzZSIsInRydWUiLCJ0cnVlIiwiZmFsc2UiLCJ0cnVlIl0sInBhciI6eyJwIjoxMiwicyI6NjN9fQ)

**The fix.** Ask "is the position something other than -1?":

```js
function hasTag(tags, tag) {
  if (tags.indexOf(tag) !== -1) {
    return true;
  }
  return false;
}
```

Shorter, and it passes the lab too: `return tags.includes(tag);`.

---

## Bug 3: Removing items while looping forward skips the next one

```js
function removeZeros(nums) {
  for (let i = 0; i < nums.length; i++) {
    if (nums[i] === 0) {
      nums.splice(i, 1);
    }
  }
  return nums;
}

removeZeros([4, 0, 0, 7]);
```

**Predict before running.** Before each turn, write down `i`, `nums[i]` and `nums.length`. What comes back?

**What happens.** `[4, 0, 7]`. One zero escapes. `[0, 0, 0]` comes back as `[0]`. But `[1, 2]` (no zeros) and `[0, 9]` (one zero) both come out right, which is how this bug gets past a quick test.

**What the trace shows.** Step through `removeZeros([4, 0, 0, 7])`:

| Turn | `i` | `nums` at the start of the turn | `nums[i]` | What happens |
| --- | --- | --- | --- | --- |
| 1 | 0 | `[4, 0, 0, 7]` | `4` | kept |
| 2 | 1 | `[4, 0, 0, 7]` | `0` | `splice(1, 1)`: `nums` is now `[4, 0, 7]` |
| 3 | 2 | `[4, 0, 7]` | `7` | kept |
| (end) | 3 | `[4, 0, 7]` | | `3 < 3` is false, the loop stops |

The loop gate answers yes three times, then no. The `if` gate answers no, yes, no. It never sees the second zero. When `splice` removed the first one, everything after it slid one place to the left, so the second zero moved from position 2 to position 1. But `i` had already been at 1, and the next turn moves it on to 2.

**The mental model.** `splice` doesn't leave a hole. It shifts every later item one place left and makes `length` one smaller. Walking *forwards*, that shift pulls an unchecked item into a position you've already checked. Walking *backwards*, the only items that shift are ones you've already checked, so nothing is skipped.

**Lab: fix `removeZeros`.** Step to turn 2 and watch what `splice` does to `nums`, then fix the loop.

<iframe src="https://iineman2.github.io/code-glyphs/?embed=1#e=eyJ2IjoxLCJrIjoiZml4IiwidCI6IlJlbW92ZSBldmVyeSB6ZXJvIiwicCI6Im51bXMgaXMgYSBsaXN0IG9mIHdob2xlIG51bWJlcnMuIEZpeCB0aGUgc2hhcGUgc28gaXQgbGVhdmVzIHdpdGggdGhlIHNhbWUgbGlzdCB3aXRoIGV2ZXJ5IDAgdGFrZW4gb3V0IGFuZCB0aGUgb3RoZXIgbnVtYmVycyBrZXB0IGluIG9yZGVyLiBGb3IgbnVtcyA9IFs0LCAwLCAwLCA3XSB0aGF0IGlzIFs0LCA3XS4iLCJmbiI6InJlbW92ZVplcm9zIiwiYSI6WyJudW1zIl0sInMiOiJmdW5jdGlvbiByZW1vdmVaZXJvcyhudW1zKSB7XG4gIGZvciAobGV0IGkgPSAwOyBpIDwgbnVtcy5sZW5ndGg7IGkrKykge1xuICAgIGlmIChudW1zW2ldID09PSAwKSB7XG4gICAgICBudW1zLnNwbGljZShpLCAxKTtcbiAgICB9XG4gIH1cbiAgcmV0dXJuIG51bXM7XG59XG4iLCJjIjpbWyJbNCwgMCwgMCwgN10iXSxbIlsxLCAyXSJdXSwiaCI6W1siWzBdIl0sWyJbMCwgMCwgMF0iXSxbIltdIl0sWyJbNSwgMCwgMywgMCwgMF0iXSxbIlswLCA5XSJdXSwidyI6WyJbNCwgN10iLCJbMSwgMl0iLCJbXSIsIltdIiwiW10iLCJbNSwgM10iLCJbOV0iXSwicGFyIjp7InAiOjI1LCJzIjoyOTd9fQ" width="100%" height="680" style="border:0;max-width:100%" allow="clipboard-write" loading="lazy" title="Code Glyphs puzzle: Remove every zero"></iframe>

[Open this lab in a new tab](https://iineman2.github.io/code-glyphs/#e=eyJ2IjoxLCJrIjoiZml4IiwidCI6IlJlbW92ZSBldmVyeSB6ZXJvIiwicCI6Im51bXMgaXMgYSBsaXN0IG9mIHdob2xlIG51bWJlcnMuIEZpeCB0aGUgc2hhcGUgc28gaXQgbGVhdmVzIHdpdGggdGhlIHNhbWUgbGlzdCB3aXRoIGV2ZXJ5IDAgdGFrZW4gb3V0IGFuZCB0aGUgb3RoZXIgbnVtYmVycyBrZXB0IGluIG9yZGVyLiBGb3IgbnVtcyA9IFs0LCAwLCAwLCA3XSB0aGF0IGlzIFs0LCA3XS4iLCJmbiI6InJlbW92ZVplcm9zIiwiYSI6WyJudW1zIl0sInMiOiJmdW5jdGlvbiByZW1vdmVaZXJvcyhudW1zKSB7XG4gIGZvciAobGV0IGkgPSAwOyBpIDwgbnVtcy5sZW5ndGg7IGkrKykge1xuICAgIGlmIChudW1zW2ldID09PSAwKSB7XG4gICAgICBudW1zLnNwbGljZShpLCAxKTtcbiAgICB9XG4gIH1cbiAgcmV0dXJuIG51bXM7XG59XG4iLCJjIjpbWyJbNCwgMCwgMCwgN10iXSxbIlsxLCAyXSJdXSwiaCI6W1siWzBdIl0sWyJbMCwgMCwgMF0iXSxbIltdIl0sWyJbNSwgMCwgMywgMCwgMF0iXSxbIlswLCA5XSJdXSwidyI6WyJbNCwgN10iLCJbMSwgMl0iLCJbXSIsIltdIiwiW10iLCJbNSwgM10iLCJbOV0iXSwicGFyIjp7InAiOjI1LCJzIjoyOTd9fQ)

**The fix.** Walk from the last position down to 0:

```js
function removeZeros(nums) {
  for (let i = nums.length - 1; i >= 0; i--) {
    if (nums[i] === 0) {
      nums.splice(i, 1);
    }
  }
  return nums;
}
```

Now `i` takes the values 3, 2, 1 and 0: four turns for four items, and `removeZeros([4, 0, 0, 7])` gives `[4, 7]`. Building a fresh list instead (push every item that isn't `0` into a new array) also passes the lab, and leaves the original list alone. In everyday JavaScript that is `nums.filter((n) => n !== 0)`.

---

## Bug 4: `sort()` sorts numbers as text

```js
function sortScores(scores) {
  return scores.sort();
}

sortScores([10, 9, 100, 1]);
```

**Predict before running.** What order comes back?

**What happens.** `[1, 10, 100, 9]`. Called with no arguments, `sort()` turns each item into text and compares the text one character at a time, like words in a dictionary. `"100"` comes before `"9"` for the same reason "apple" comes before "banana": the first characters decide, and `"1"` comes before `"9"`. Try `[3, 1, 2]` and it comes out right, because single digits sort the same as text and as numbers. That is why this one survives testing.

**What the trace shows.** Very little, and that is the lesson. The whole sort is a single stroke: the list goes in as `[10, 9, 100, 1]` and comes out as `[1, 10, 100, 9]`. No line of *your* code ever compares two scores. The comparing happens inside `sort`, with its default rule, which is the text rule. The fix below doesn't add visible strokes to the sort either, but it changes who does the comparing: `sort` calls your compare function once for every pair it needs to put in order, and Code Glyphs counts each of those calls as a step. On `[10, 9, 100, 1]` the run goes from 3 steps to 29.

**The mental model.** Give `sort` a compare function. It gets two items, `a` and `b`, and returns:

- a negative number: `a` goes first,
- a positive number: `b` goes first,
- `0`: leave them as they are.

`a - b` does exactly that for numbers, smallest first. `b - a` gives largest first: `[100, 10, 9, 1]`. One more surprise while you're here: `sort` rearranges the list you called it on and returns that same list. It doesn't make a copy.

**Lab: fix `sortScores`.** Add a compare function. Code Glyphs doesn't do arrow functions yet, so write it as a named function and pass it by name.

<iframe src="https://iineman2.github.io/code-glyphs/?embed=1#e=eyJ2IjoxLCJrIjoiZml4IiwidCI6IlNvcnQgc2NvcmVzIGZyb20gbG93IHRvIGhpZ2giLCJwIjoic2NvcmVzIGlzIGEgbGlzdCBvZiB3aG9sZSBudW1iZXJzLiBGaXggdGhlIHNoYXBlIHNvIGl0IGxlYXZlcyB3aXRoIHRoZSBzY29yZXMgc29ydGVkIGZyb20gbG93ZXN0IHRvIGhpZ2hlc3QsIGNvbXBhcmVkIGFzIG51bWJlcnMuIEZvciBzY29yZXMgPSBbMTAsIDksIDEwMCwgMV0gdGhhdCBpcyBbMSwgOSwgMTAsIDEwMF0uIiwiZm4iOiJzb3J0U2NvcmVzIiwiYSI6WyJzY29yZXMiXSwicyI6ImZ1bmN0aW9uIHNvcnRTY29yZXMoc2NvcmVzKSB7XG4gIHJldHVybiBzY29yZXMuc29ydCgpO1xufVxuIiwiYyI6W1siWzEwLCA5LCAxMDAsIDFdIl0sWyJbMywgMSwgMl0iXV0sImgiOltbIltdIl0sWyJbNV0iXSxbIlsyNSwgMywgMjAwLCA0MF0iXSxbIls3LCA3LCAxXSJdLFsiWy01LCAyLCAtMTBdIl1dLCJ3IjpbIlsxLCA5LCAxMCwgMTAwXSIsIlsxLCAyLCAzXSIsIltdIiwiWzVdIiwiWzMsIDI1LCA0MCwgMjAwXSIsIlsxLCA3LCA3XSIsIlstMTAsIC01LCAyXSJdLCJwYXIiOnsicCI6OSwicyI6MTM4fX0" width="100%" height="680" style="border:0;max-width:100%" allow="clipboard-write" loading="lazy" title="Code Glyphs puzzle: Sort scores from low to high"></iframe>

[Open this lab in a new tab](https://iineman2.github.io/code-glyphs/#e=eyJ2IjoxLCJrIjoiZml4IiwidCI6IlNvcnQgc2NvcmVzIGZyb20gbG93IHRvIGhpZ2giLCJwIjoic2NvcmVzIGlzIGEgbGlzdCBvZiB3aG9sZSBudW1iZXJzLiBGaXggdGhlIHNoYXBlIHNvIGl0IGxlYXZlcyB3aXRoIHRoZSBzY29yZXMgc29ydGVkIGZyb20gbG93ZXN0IHRvIGhpZ2hlc3QsIGNvbXBhcmVkIGFzIG51bWJlcnMuIEZvciBzY29yZXMgPSBbMTAsIDksIDEwMCwgMV0gdGhhdCBpcyBbMSwgOSwgMTAsIDEwMF0uIiwiZm4iOiJzb3J0U2NvcmVzIiwiYSI6WyJzY29yZXMiXSwicyI6ImZ1bmN0aW9uIHNvcnRTY29yZXMoc2NvcmVzKSB7XG4gIHJldHVybiBzY29yZXMuc29ydCgpO1xufVxuIiwiYyI6W1siWzEwLCA5LCAxMDAsIDFdIl0sWyJbMywgMSwgMl0iXV0sImgiOltbIltdIl0sWyJbNV0iXSxbIlsyNSwgMywgMjAwLCA0MF0iXSxbIls3LCA3LCAxXSJdLFsiWy01LCAyLCAtMTBdIl1dLCJ3IjpbIlsxLCA5LCAxMCwgMTAwXSIsIlsxLCAyLCAzXSIsIltdIiwiWzVdIiwiWzMsIDI1LCA0MCwgMjAwXSIsIlsxLCA3LCA3XSIsIlstMTAsIC01LCAyXSJdLCJwYXIiOnsicCI6OSwicyI6MTM4fX0)

**The fix.** A named compare function, passed to `sort`:

```js
function byNumber(a, b) {
  return a - b;
}

function sortScores(scores) {
  return scores.sort(byNumber);
}
```

`sortScores([10, 9, 100, 1])` now gives `[1, 9, 10, 100]`. In everyday JavaScript you'd usually write it inline: `scores.sort((a, b) => a - b)`.

---

## Practice: positions and items

Two puzzles from the free tiers of the Code Glyphs puzzle bank. Both are about the gap between where an item is and what it is.

**Where is the first reading equal to limit** (Tier 1, Predict). You don't write any code. A loop walks a list and leaves with the *position* of the first match, or `-1` if there is none. That is `indexOf` written out by hand, so after Bug 2 you already know which two answers to watch for. Trace it on paper, then pick the answer.

<iframe src="https://iineman2.github.io/code-glyphs/?embed=1&amp;pz=P-qxpvpg" width="100%" height="680" style="border:0;max-width:100%" allow="clipboard-write" loading="lazy" title="Code Glyphs puzzle: Where is the first reading equal to limit"></iframe>

[Open this puzzle in a new tab](https://iineman2.github.io/code-glyphs/?pz=P-qxpvpg)

**Never rising scores** (Tier 2, Fix). A loop compares each score with the one just before it, and one of its reads points at the wrong thing. Step through the first case, watch what each read gives back, and repair it.

<iframe src="https://iineman2.github.io/code-glyphs/?embed=1&amp;pz=F-efoxii" width="100%" height="680" style="border:0;max-width:100%" allow="clipboard-write" loading="lazy" title="Code Glyphs puzzle: Never rising scores"></iframe>

[Open this puzzle in a new tab](https://iineman2.github.io/code-glyphs/?pz=F-efoxii)

Tiers 1 and 2 of the bank are free: 216 puzzles you can open in the app's puzzle browser. The full bank has 1,080.

---

## A 60-second array review

Before you trust a loop over a list, pick one small input and answer these:

1. Does each variable hold a **position** or an **item**? Is any position used as an item, or any item used as a position?
2. Is a search result (`indexOf`, `findIndex`) compared with `-1`, rather than handed to `if` on its own?
3. Does the loop change the list it is walking? If it removes items, does it walk backwards (or build a new list)?
4. Does every `sort()` of numbers have a compare function?
5. Did I test with a list where the bug would *show*: an item at position 0, two matches in a row, numbers with different digit counts?

Then step through it once with the list that worries you most. The bug is usually visible within the first two turns.
