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:
- a short snippet with the bug,
- a Predict before running prompt (do it on paper, it takes a minute),
- what the step-by-step trace actually shows,
- a lab: the broken function, opened in a step-through visualizer, where you fix it and get checked against hidden cases,
- the fix, written out under the lab so you can try first.
The labs use 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
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.
The fix. n is already the item, so use it directly:
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"
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:
-
0means "found, at the very front", and0is falsy. -
-1means "not found anywhere", and-1is 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.
The fix. Ask "is the position something other than -1?":
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
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.
The fix. Walk from the last position down to 0:
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
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:
agoes first, - a positive number:
bgoes 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.
The fix. A named compare function, passed to sort:
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.
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.
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:
- Does each variable hold a position or an item? Is any position used as an item, or any item used as a position?
- Is a search result (
indexOf,findIndex) compared with-1, rather than handed toifon its own? - Does the loop change the list it is walking? If it removes items, does it walk backwards (or build a new list)?
- Does every
sort()of numbers have a compare function? - 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.
Top comments (0)