<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Code Glyphs]]></title><description><![CDATA[Code Glyphs]]></description><link>https://codeglyphs.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 05 Dec 2026 23:43:53 GMT</lastBuildDate><atom:link href="https://codeglyphs.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[4 JavaScript Array Bugs Beginners Hit — and How to Watch Them Happen]]></title><description><![CDATA[for...of gives items. indexOf can return 0. Forward splice skips items. sort() compares text. Four array bugs with predictions and step-through labs.]]></description><link>https://codeglyphs.hashnode.dev/four-javascript-array-bugs-beginners-hit</link><guid isPermaLink="true">https://codeglyphs.hashnode.dev/four-javascript-array-bugs-beginners-hit</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[programming]]></category><dc:creator><![CDATA[Iineman2]]></dc:creator><pubDate>Thu, 03 Dec 2026 07:05:15 GMT</pubDate><content:encoded><![CDATA[<p>Array bugs rarely crash. The function runs, a list comes back, and it is <em>almost</em> right: one item is <code>NaN</code>, one zero survived, <code>100</code> landed in front of <code>9</code>.</p>
<p>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 <strong>position</strong> or an <strong>item</strong>, what a search result really means, how the list changes underneath your loop, and which rule <code>sort</code> uses when you don't give it one. Watch the values change one step at a time and the bug points at itself.</p>
<p>Each bug below has:</p>
<ol>
<li>a short snippet with the bug,</li>
<li>a <strong>Predict before running</strong> prompt (do it on paper, it takes a minute),</li>
<li>what the step-by-step trace actually shows,</li>
<li>a lab: the broken function, opened in a step-through visualizer, where you fix it and get checked against hidden cases,</li>
<li>the fix, written out under the lab so you can try first.</li>
</ol>
<p>The labs use <a href="https://iineman2.github.io/code-glyphs/">Code Glyphs</a>, 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.</p>
<p><strong>How the labs work.</strong> Each lab opens with the broken function already loaded. Press <strong>Step</strong> to advance one stroke at a time and watch the values change, or <strong>Run</strong> to go straight to the result. Edit the shape (or the JavaScript pane), then press <strong>Check my shape</strong>. 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 <code>undefined</code> as <strong>nothing</strong>, and <code>true</code> / <code>false</code> as <strong>yes</strong> / <strong>no</strong>.</p>
<p>If the embedded labs don't load where you're reading this, every lab also has a plain link right under it.</p>
<hr />
<h2>Bug 1: <code>for...of</code> hands you the item, not its index</h2>
<pre><code class="language-js">function doubled(nums) {
  const out = [];
  for (const n of nums) {
    out.push(nums[n] * 2);
  }
  return out;
}

doubled([3, 1, 2]);
</code></pre>
<p><strong>Predict before running.</strong> Write down <code>n</code> for each turn of the loop, and what gets pushed. What list comes back?</p>
<p><strong>What happens.</strong> <code>[NaN, 2, 4]</code>. Expected: <code>[6, 2, 4]</code>. Two out of three are right, which makes it look like an arithmetic problem. It isn't one.</p>
<p><strong>What the trace shows.</strong> Step through <code>doubled([3, 1, 2])</code> and watch the well for <code>n</code>:</p>
<table>
<thead>
<tr>
<th>Turn</th>
<th><code>n</code></th>
<th><code>nums[n]</code></th>
<th>Pushed</th>
</tr>
</thead>
<tbody><tr>
<td>1</td>
<td><code>3</code></td>
<td><code>nums[3]</code>: <strong>nothing</strong> (there is no index 3)</td>
<td><code>NaN</code></td>
</tr>
<tr>
<td>2</td>
<td><code>1</code></td>
<td><code>nums[1]</code>: <code>1</code></td>
<td><code>2</code></td>
</tr>
<tr>
<td>3</td>
<td><code>2</code></td>
<td><code>nums[2]</code>: <code>2</code></td>
<td><code>4</code></td>
</tr>
</tbody></table>
<p><code>n</code> is never <code>0</code>. It takes the <em>items</em> <code>3</code>, <code>1</code>, <code>2</code>, and then the code uses each item as a <em>position</em>. The list only has positions 0, 1 and 2, so <code>nums[3]</code> reads <strong>nothing</strong> (<code>undefined</code>), and <code>undefined * 2</code> is <code>NaN</code>. The other two turns are right by luck: in this list, the items <code>1</code> and <code>2</code> happen to sit at positions 1 and 2. Give it <code>[10, 20, 30, 40]</code> and every read misses: <code>[NaN, NaN, NaN, NaN]</code>.</p>
<p><strong>The mental model.</strong> There are two ways to walk a list, and each one gives you a different thing:</p>
<table>
<thead>
<tr>
<th>Loop</th>
<th>The loop variable is</th>
<th>To get the item</th>
</tr>
</thead>
<tbody><tr>
<td><code>for (const n of nums)</code></td>
<td>the item</td>
<td><code>n</code></td>
</tr>
<tr>
<td><code>for (let i = 0; i &lt; nums.length; i++)</code></td>
<td>the position</td>
<td><code>nums[i]</code></td>
</tr>
</tbody></table>
<p><code>nums[n]</code> mixes the two. A naming habit helps: <code>i</code> only ever holds a position, and an item gets a real name (<code>n</code>, <code>score</code>, <code>tag</code>). Then <code>nums[score]</code> looks wrong the moment you type it. (And skip <code>for...in</code> on arrays. It gives you the positions as <em>strings</em>: <code>"0"</code>, <code>"1"</code>, <code>"2"</code>.)</p>
<p><strong>Lab: fix <code>doubled</code>.</strong> Case 1 is the list you just traced.</p>
<iframe width="100%" height="680" style="border:0;max-width:100%"></iframe>

<p><a href="https://iineman2.github.io/code-glyphs/#e=eyJ2IjoxLCJrIjoiZml4IiwidCI6IkRvdWJsZSBldmVyeSBpdGVtIiwicCI6Im51bXMgaXMgYSBsaXN0IG9mIHdob2xlIG51bWJlcnMuIEZpeCB0aGUgc2hhcGUgc28gaXQgbGVhdmVzIHdpdGggYSBuZXcgbGlzdCBob2xkaW5nIGVhY2ggbnVtYmVyIGRvdWJsZWQsIGluIHRoZSBzYW1lIG9yZGVyLiBGb3IgbnVtcyA9IFszLCAxLCAyXSB0aGF0IGlzIFs2LCAyLCA0XS4iLCJmbiI6ImRvdWJsZWQiLCJhIjpbIm51bXMiXSwicyI6ImZ1bmN0aW9uIGRvdWJsZWQobnVtcykge1xuICBjb25zdCBvdXQgPSBbXTtcbiAgZm9yIChjb25zdCBuIG9mIG51bXMpIHtcbiAgICBvdXQucHVzaChudW1zW25dICogMik7XG4gIH1cbiAgcmV0dXJuIG91dDtcbn1cbiIsImMiOltbIlszLCAxLCAyXSJdLFsiW10iXV0sImgiOltbIls1XSJdLFsiWzAsIDRdIl0sWyJbLTIsIDcsIDFdIl0sWyJbMTAsIDIwLCAzMCwgNDBdIl1dLCJ3IjpbIls2LCAyLCA0XSIsIltdIiwiWzEwXSIsIlswLCA4XSIsIlstNCwgMTQsIDJdIiwiWzIwLCA0MCwgNjAsIDgwXSJdLCJwYXIiOnsicCI6MTMsInMiOjEyN319">Open this lab in a new tab</a></p>
<p><strong>The fix.</strong> <code>n</code> is already the item, so use it directly:</p>
<pre><code class="language-js">function doubled(nums) {
  const out = [];
  for (const n of nums) {
    out.push(n * 2);
  }
  return out;
}
</code></pre>
<p><code>doubled([3, 1, 2])</code> now gives <code>[6, 2, 4]</code>. (An index loop with <code>out.push(nums[i] * 2)</code> gives the same result. Pick one style and don't mix them.)</p>
<hr />
<h2>Bug 2: <code>indexOf</code> finds it at position 0, and <code>if</code> hears "no"</h2>
<pre><code class="language-js">function hasTag(tags, tag) {
  if (tags.indexOf(tag)) {
    return true;
  }
  return false;
}

hasTag(["js", "css"], "js");
</code></pre>
<p><strong>Predict before running.</strong> What does it return for <code>"js"</code>? For <code>"html"</code>? For <code>"css"</code>?</p>
<p><strong>What happens.</strong></p>
<table>
<thead>
<tr>
<th>Call</th>
<th>Returns</th>
<th>Should be</th>
</tr>
</thead>
<tbody><tr>
<td><code>hasTag(["js", "css"], "js")</code></td>
<td><code>false</code></td>
<td><code>true</code></td>
</tr>
<tr>
<td><code>hasTag(["js", "css"], "html")</code></td>
<td><code>true</code></td>
<td><code>false</code></td>
</tr>
<tr>
<td><code>hasTag(["js", "css"], "css")</code></td>
<td><code>true</code></td>
<td><code>true</code></td>
</tr>
</tbody></table>
<p>It is wrong in <em>both</em> directions, and the one call that comes out right does so by accident.</p>
<p><strong>What the trace shows.</strong> Step through <code>hasTag(["js", "css"], "js")</code> up to the <code>if</code>. Its condition, <code>tags.indexOf(tag)</code>, gives <code>0</code>, because <code>"js"</code> is the first item. <code>0</code> is falsy, so the gate answers <strong>no</strong>, and the run leaves through <code>return false</code> (the result panel says <strong>no</strong>). Now run it with <code>"html"</code>: <code>indexOf</code> gives <code>-1</code>, which means "not found", but <code>-1</code> is truthy, so the gate answers <strong>yes</strong>.</p>
<p><strong>The mental model.</strong> <code>indexOf</code> doesn't answer a yes/no question. It answers "<em>where</em> is it?", and two of its answers break truthiness:</p>
<ul>
<li><code>0</code> means "found, at the very front", and <code>0</code> is falsy.</li>
<li><code>-1</code> means "not found anywhere", and <code>-1</code> is truthy.</li>
</ul>
<p>So never hand a position straight to <code>if</code>. Compare it explicitly with <code>!== -1</code>, or ask the yes/no question directly with <code>includes</code>, which returns <code>true</code> or <code>false</code>. The same goes for <code>findIndex</code>, which also answers <code>-1</code> when nothing matches.</p>
<p><strong>Lab: fix <code>hasTag</code>.</strong> The hidden cases include an empty list and a tag at the very front.</p>
<iframe width="100%" height="680" style="border:0;max-width:100%"></iframe>

<p><a href="https://iineman2.github.io/code-glyphs/#e=eyJ2IjoxLCJrIjoiZml4IiwidCI6IklzIHRoZSB0YWcgaW4gdGhlIGxpc3Q_IiwicCI6InRhZ3MgaXMgYSBsaXN0IG9mIHdvcmRzIGFuZCB0YWcgaXMgb25lIHdvcmQuIEZpeCB0aGUgc2hhcGUgc28gaXQgbGVhdmVzIHdpdGggdHJ1ZSB3aGVuIHRhZyBpcyBzb21ld2hlcmUgaW4gdGFncywgYW5kIGZhbHNlIHdoZW4gaXQgaXMgbm90LiBGb3IgdGFncyA9IFtcImpzXCIsIFwiY3NzXCJdIGFuZCB0YWcgPSBcImpzXCIgdGhhdCBpcyB0cnVlLiIsImZuIjoiaGFzVGFnIiwiYSI6WyJ0YWdzIiwidGFnIl0sInMiOiJmdW5jdGlvbiBoYXNUYWcodGFncywgdGFnKSB7XG4gIGlmICh0YWdzLmluZGV4T2YodGFnKSkge1xuICAgIHJldHVybiB0cnVlO1xuICB9XG4gIHJldHVybiBmYWxzZTtcbn1cbiIsImMiOltbIltcImpzXCIsIFwiY3NzXCJdIiwiXCJqc1wiIl0sWyJbXCJqc1wiLCBcImNzc1wiXSIsIlwiaHRtbFwiIl1dLCJoIjpbWyJbXSIsIlwianNcIiJdLFsiW1wiYVwiLCBcImJcIiwgXCJjXCJdIiwiXCJjXCIiXSxbIltcImFcIiwgXCJiXCIsIFwiY1wiXSIsIlwiYVwiIl0sWyJbXCJ4XCJdIiwiXCJ5XCIiXSxbIltcInhcIl0iLCJcInhcIiJdXSwidyI6WyJ0cnVlIiwiZmFsc2UiLCJmYWxzZSIsInRydWUiLCJ0cnVlIiwiZmFsc2UiLCJ0cnVlIl0sInBhciI6eyJwIjoxMiwicyI6NjN9fQ">Open this lab in a new tab</a></p>
<p><strong>The fix.</strong> Ask "is the position something other than -1?":</p>
<pre><code class="language-js">function hasTag(tags, tag) {
  if (tags.indexOf(tag) !== -1) {
    return true;
  }
  return false;
}
</code></pre>
<p>Shorter, and it passes the lab too: <code>return tags.includes(tag);</code>.</p>
<hr />
<h2>Bug 3: Removing items while looping forward skips the next one</h2>
<pre><code class="language-js">function removeZeros(nums) {
  for (let i = 0; i &lt; nums.length; i++) {
    if (nums[i] === 0) {
      nums.splice(i, 1);
    }
  }
  return nums;
}

removeZeros([4, 0, 0, 7]);
</code></pre>
<p><strong>Predict before running.</strong> Before each turn, write down <code>i</code>, <code>nums[i]</code> and <code>nums.length</code>. What comes back?</p>
<p><strong>What happens.</strong> <code>[4, 0, 7]</code>. One zero escapes. <code>[0, 0, 0]</code> comes back as <code>[0]</code>. But <code>[1, 2]</code> (no zeros) and <code>[0, 9]</code> (one zero) both come out right, which is how this bug gets past a quick test.</p>
<p><strong>What the trace shows.</strong> Step through <code>removeZeros([4, 0, 0, 7])</code>:</p>
<table>
<thead>
<tr>
<th>Turn</th>
<th><code>i</code></th>
<th><code>nums</code> at the start of the turn</th>
<th><code>nums[i]</code></th>
<th>What happens</th>
</tr>
</thead>
<tbody><tr>
<td>1</td>
<td>0</td>
<td><code>[4, 0, 0, 7]</code></td>
<td><code>4</code></td>
<td>kept</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td><code>[4, 0, 0, 7]</code></td>
<td><code>0</code></td>
<td><code>splice(1, 1)</code>: <code>nums</code> is now <code>[4, 0, 7]</code></td>
</tr>
<tr>
<td>3</td>
<td>2</td>
<td><code>[4, 0, 7]</code></td>
<td><code>7</code></td>
<td>kept</td>
</tr>
<tr>
<td>(end)</td>
<td>3</td>
<td><code>[4, 0, 7]</code></td>
<td></td>
<td><code>3 &lt; 3</code> is false, the loop stops</td>
</tr>
</tbody></table>
<p>The loop gate answers yes three times, then no. The <code>if</code> gate answers no, yes, no. It never sees the second zero. When <code>splice</code> 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 <code>i</code> had already been at 1, and the next turn moves it on to 2.</p>
<p><strong>The mental model.</strong> <code>splice</code> doesn't leave a hole. It shifts every later item one place left and makes <code>length</code> one smaller. Walking <em>forwards</em>, that shift pulls an unchecked item into a position you've already checked. Walking <em>backwards</em>, the only items that shift are ones you've already checked, so nothing is skipped.</p>
<p><strong>Lab: fix <code>removeZeros</code>.</strong> Step to turn 2 and watch what <code>splice</code> does to <code>nums</code>, then fix the loop.</p>
<iframe width="100%" height="680" style="border:0;max-width:100%"></iframe>

<p><a href="https://iineman2.github.io/code-glyphs/#e=eyJ2IjoxLCJrIjoiZml4IiwidCI6IlJlbW92ZSBldmVyeSB6ZXJvIiwicCI6Im51bXMgaXMgYSBsaXN0IG9mIHdob2xlIG51bWJlcnMuIEZpeCB0aGUgc2hhcGUgc28gaXQgbGVhdmVzIHdpdGggdGhlIHNhbWUgbGlzdCB3aXRoIGV2ZXJ5IDAgdGFrZW4gb3V0IGFuZCB0aGUgb3RoZXIgbnVtYmVycyBrZXB0IGluIG9yZGVyLiBGb3IgbnVtcyA9IFs0LCAwLCAwLCA3XSB0aGF0IGlzIFs0LCA3XS4iLCJmbiI6InJlbW92ZVplcm9zIiwiYSI6WyJudW1zIl0sInMiOiJmdW5jdGlvbiByZW1vdmVaZXJvcyhudW1zKSB7XG4gIGZvciAobGV0IGkgPSAwOyBpIDwgbnVtcy5sZW5ndGg7IGkrKykge1xuICAgIGlmIChudW1zW2ldID09PSAwKSB7XG4gICAgICBudW1zLnNwbGljZShpLCAxKTtcbiAgICB9XG4gIH1cbiAgcmV0dXJuIG51bXM7XG59XG4iLCJjIjpbWyJbNCwgMCwgMCwgN10iXSxbIlsxLCAyXSJdXSwiaCI6W1siWzBdIl0sWyJbMCwgMCwgMF0iXSxbIltdIl0sWyJbNSwgMCwgMywgMCwgMF0iXSxbIlswLCA5XSJdXSwidyI6WyJbNCwgN10iLCJbMSwgMl0iLCJbXSIsIltdIiwiW10iLCJbNSwgM10iLCJbOV0iXSwicGFyIjp7InAiOjI1LCJzIjoyOTd9fQ">Open this lab in a new tab</a></p>
<p><strong>The fix.</strong> Walk from the last position down to 0:</p>
<pre><code class="language-js">function removeZeros(nums) {
  for (let i = nums.length - 1; i &gt;= 0; i--) {
    if (nums[i] === 0) {
      nums.splice(i, 1);
    }
  }
  return nums;
}
</code></pre>
<p>Now <code>i</code> takes the values 3, 2, 1 and 0: four turns for four items, and <code>removeZeros([4, 0, 0, 7])</code> gives <code>[4, 7]</code>. Building a fresh list instead (push every item that isn't <code>0</code> into a new array) also passes the lab, and leaves the original list alone. In everyday JavaScript that is <code>nums.filter((n) =&gt; n !== 0)</code>.</p>
<hr />
<h2>Bug 4: <code>sort()</code> sorts numbers as text</h2>
<pre><code class="language-js">function sortScores(scores) {
  return scores.sort();
}

sortScores([10, 9, 100, 1]);
</code></pre>
<p><strong>Predict before running.</strong> What order comes back?</p>
<p><strong>What happens.</strong> <code>[1, 10, 100, 9]</code>. Called with no arguments, <code>sort()</code> turns each item into text and compares the text one character at a time, like words in a dictionary. <code>"100"</code> comes before <code>"9"</code> for the same reason "apple" comes before "banana": the first characters decide, and <code>"1"</code> comes before <code>"9"</code>. Try <code>[3, 1, 2]</code> and it comes out right, because single digits sort the same as text and as numbers. That is why this one survives testing.</p>
<p><strong>What the trace shows.</strong> Very little, and that is the lesson. The whole sort is a single stroke: the list goes in as <code>[10, 9, 100, 1]</code> and comes out as <code>[1, 10, 100, 9]</code>. No line of <em>your</em> code ever compares two scores. The comparing happens inside <code>sort</code>, 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: <code>sort</code> 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 <code>[10, 9, 100, 1]</code> the run goes from 3 steps to 29.</p>
<p><strong>The mental model.</strong> Give <code>sort</code> a compare function. It gets two items, <code>a</code> and <code>b</code>, and returns:</p>
<ul>
<li>a negative number: <code>a</code> goes first,</li>
<li>a positive number: <code>b</code> goes first,</li>
<li><code>0</code>: leave them as they are.</li>
</ul>
<p><code>a - b</code> does exactly that for numbers, smallest first. <code>b - a</code> gives largest first: <code>[100, 10, 9, 1]</code>. One more surprise while you're here: <code>sort</code> rearranges the list you called it on and returns that same list. It doesn't make a copy.</p>
<p><strong>Lab: fix <code>sortScores</code>.</strong> Add a compare function. Code Glyphs doesn't do arrow functions yet, so write it as a named function and pass it by name.</p>
<iframe width="100%" height="680" style="border:0;max-width:100%"></iframe>

<p><a href="https://iineman2.github.io/code-glyphs/#e=eyJ2IjoxLCJrIjoiZml4IiwidCI6IlNvcnQgc2NvcmVzIGZyb20gbG93IHRvIGhpZ2giLCJwIjoic2NvcmVzIGlzIGEgbGlzdCBvZiB3aG9sZSBudW1iZXJzLiBGaXggdGhlIHNoYXBlIHNvIGl0IGxlYXZlcyB3aXRoIHRoZSBzY29yZXMgc29ydGVkIGZyb20gbG93ZXN0IHRvIGhpZ2hlc3QsIGNvbXBhcmVkIGFzIG51bWJlcnMuIEZvciBzY29yZXMgPSBbMTAsIDksIDEwMCwgMV0gdGhhdCBpcyBbMSwgOSwgMTAsIDEwMF0uIiwiZm4iOiJzb3J0U2NvcmVzIiwiYSI6WyJzY29yZXMiXSwicyI6ImZ1bmN0aW9uIHNvcnRTY29yZXMoc2NvcmVzKSB7XG4gIHJldHVybiBzY29yZXMuc29ydCgpO1xufVxuIiwiYyI6W1siWzEwLCA5LCAxMDAsIDFdIl0sWyJbMywgMSwgMl0iXV0sImgiOltbIltdIl0sWyJbNV0iXSxbIlsyNSwgMywgMjAwLCA0MF0iXSxbIls3LCA3LCAxXSJdLFsiWy01LCAyLCAtMTBdIl1dLCJ3IjpbIlsxLCA5LCAxMCwgMTAwXSIsIlsxLCAyLCAzXSIsIltdIiwiWzVdIiwiWzMsIDI1LCA0MCwgMjAwXSIsIlsxLCA3LCA3XSIsIlstMTAsIC01LCAyXSJdLCJwYXIiOnsicCI6OSwicyI6MTM4fX0">Open this lab in a new tab</a></p>
<p><strong>The fix.</strong> A named compare function, passed to <code>sort</code>:</p>
<pre><code class="language-js">function byNumber(a, b) {
  return a - b;
}

function sortScores(scores) {
  return scores.sort(byNumber);
}
</code></pre>
<p><code>sortScores([10, 9, 100, 1])</code> now gives <code>[1, 9, 10, 100]</code>. In everyday JavaScript you'd usually write it inline: <code>scores.sort((a, b) =&gt; a - b)</code>.</p>
<hr />
<h2>Practice: positions and items</h2>
<p>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.</p>
<p><strong>Where is the first reading equal to limit</strong> (Tier 1, Predict). You don't write any code. A loop walks a list and leaves with the <em>position</em> of the first match, or <code>-1</code> if there is none. That is <code>indexOf</code> 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.</p>
<iframe width="100%" height="680" style="border:0;max-width:100%"></iframe>

<p><a href="https://iineman2.github.io/code-glyphs/?pz=P-qxpvpg">Open this puzzle in a new tab</a></p>
<p><strong>Never rising scores</strong> (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.</p>
<iframe width="100%" height="680" style="border:0;max-width:100%"></iframe>

<p><a href="https://iineman2.github.io/code-glyphs/?pz=F-efoxii">Open this puzzle in a new tab</a></p>
<p>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.</p>
<hr />
<h2>A 60-second array review</h2>
<p>Before you trust a loop over a list, pick one small input and answer these:</p>
<ol>
<li>Does each variable hold a <strong>position</strong> or an <strong>item</strong>? Is any position used as an item, or any item used as a position?</li>
<li>Is a search result (<code>indexOf</code>, <code>findIndex</code>) compared with <code>-1</code>, rather than handed to <code>if</code> on its own?</li>
<li>Does the loop change the list it is walking? If it removes items, does it walk backwards (or build a new list)?</li>
<li>Does every <code>sort()</code> of numbers have a compare function?</li>
<li>Did I test with a list where the bug would <em>show</em>: an item at position 0, two matches in a row, numbers with different digit counts?</li>
</ol>
<p>Then step through it once with the list that worries you most. The bug is usually visible within the first two turns.</p>
]]></content:encoded></item><item><title><![CDATA[Why Your `if / else` Took the Wrong Branch: 4 JavaScript Condition Traps]]></title><description><![CDATA["My if is wrong" is almost never true. The if did exactly what you wrote. It just took a different branch from the one you had in your head. That gap…]]></description><link>https://codeglyphs.hashnode.dev/why-your-if-else-took-the-wrong-branch-4-javascript-condition-traps</link><guid isPermaLink="true">https://codeglyphs.hashnode.dev/why-your-if-else-took-the-wrong-branch-4-javascript-condition-traps</guid><dc:creator><![CDATA[Iineman2]]></dc:creator><pubDate>Thu, 03 Dec 2026 05:41:50 GMT</pubDate><content:encoded><![CDATA[<p>"My <code>if</code> is wrong" is almost never true. The <code>if</code> did exactly what you wrote. It just took a different branch from the one you had in your head.</p>
<p>That gap between the branch you expected and the branch that ran is where most beginner conditional bugs live, and it narrows fast once you do one thing: for a concrete input, say out loud which condition is checked first, what it evaluates to, and which line runs next.</p>
<p>This post walks through four traps. Each has a snippet, a <strong>Predict which path runs</strong> prompt (answer it before you read on), the reason it happens, and a lab: the broken function loaded into a step-through visualizer, where you can watch the branch being chosen, fix it, and get checked against hidden cases.</p>
<p>The labs use <a href="https://iineman2.github.io/code-glyphs/">Code Glyphs</a>, a browser step-through tool I built. You can follow every snippet in Node or the browser console without it.</p>
<p><strong>How the labs work.</strong> Each one opens with the broken function loaded. Press <strong>Step</strong> to advance one stroke at a time (the <code>if</code> conditions show up as "gates" you can watch answer yes or no) or <strong>Run</strong> to jump to the result. Edit the shape or the JavaScript pane, then press <strong>Check my shape</strong>: it runs your fix on the cases shown and on hidden ones. Opening a lab link doesn't run anything until you press a button.</p>
<p>If an embedded lab doesn't load where you're reading, each one has a plain link right under it.</p>
<hr />
<h2>Trap 1: Checking the broad condition before the specific one</h2>
<pre><code class="language-js">function grade(score) {
  if (score &gt;= 60) {
    return "C";
  } else if (score &gt;= 75) {
    return "B";
  } else if (score &gt;= 90) {
    return "A";
  } else {
    return "F";
  }
}

grade(93);
</code></pre>
<p><strong>Predict which path runs.</strong> For <code>score = 93</code>, which <code>return</code> line executes? And for <code>82</code>?</p>
<p><strong>What happens.</strong> <code>grade(93)</code> returns <code>"C"</code>, and so does <code>grade(82)</code>. An <code>if / else if</code> chain is a "first match wins" sieve. <code>93 &gt;= 60</code> is true, so that branch runs and the chain stops. The <code>&gt;= 75</code> and <code>&gt;= 90</code> lines are never reached, for <em>any</em> score, because anything that passes them has already passed <code>&gt;= 60</code>. The correct answer for 93 is <code>"A"</code>.</p>
<p><strong>The mental model.</strong> Each condition in the chain says yes to <em>everything</em> it covers, including inputs that a later, more specific condition was written to catch. <code>score &gt;= 60</code> is true for 93 too. So the order of the chain matters: put the <strong>narrowest</strong> condition first (the one fewest inputs satisfy), and let each later condition be a little wider.</p>
<p>The same bug shows up in the classic FizzBuzz when the single divisors come first:</p>
<pre><code class="language-js">if (n % 3 === 0)  return "Fizz";      // 15 lands here and stops
else if (n % 5 === 0)  return "Buzz";
else if (n % 15 === 0) return "FizzBuzz";   // never reached
</code></pre>
<p><code>label(15)</code> returns <code>"Fizz"</code> this way (and <code>label(30)</code> too). Put the <code>% 15</code> check first and it returns <code>"FizzBuzz"</code>.</p>
<p>If you'd rather not depend on order, bound each branch on both sides, like <code>score &gt;= 60 &amp;&amp; score &lt; 75</code>. It is longer, but every branch then stands on its own.</p>
<p><strong>Lab: fix <code>grade</code>.</strong> Step through <code>grade(93)</code> and watch which gate answers yes first.</p>
<iframe width="100%" height="680" style="border:0;max-width:100%"></iframe>

<p><a href="https://iineman2.github.io/code-glyphs/#e=eyJ2IjoxLCJrIjoiZml4IiwidCI6IkxldHRlciBncmFkZSIsInAiOiJzY29yZSBpcyAwIHRvIDEwMC4gRml4IHRoZSBzaGFwZSBzbyBpdCBsZWF2ZXMgd2l0aCBcIkFcIiBmb3IgOTAgb3IgbW9yZSwgXCJCXCIgZm9yIDc1IG9yIG1vcmUsIFwiQ1wiIGZvciA2MCBvciBtb3JlLCBhbmQgXCJGXCIgZm9yIGFueXRoaW5nIGxvd2VyLiBGb3Igc2NvcmUgPSA5MyB0aGF0IGlzIFwiQVwiLiIsImZuIjoiZ3JhZGUiLCJhIjpbInNjb3JlIl0sInMiOiJmdW5jdGlvbiBncmFkZShzY29yZSkge1xuICBpZiAoc2NvcmUgPj0gNjApIHtcbiAgICByZXR1cm4gXCJDXCI7XG4gIH0gZWxzZSBpZiAoc2NvcmUgPj0gNzUpIHtcbiAgICByZXR1cm4gXCJCXCI7XG4gIH0gZWxzZSBpZiAoc2NvcmUgPj0gOTApIHtcbiAgICByZXR1cm4gXCJBXCI7XG4gIH0gZWxzZSB7XG4gICAgcmV0dXJuIFwiRlwiO1xuICB9XG59XG4iLCJjIjpbWyI5MyJdLFsiNjQiXV0sImgiOltbIjgyIl0sWyI3NSJdLFsiOTAiXSxbIjU5Il0sWyI2MCJdLFsiMTAwIl1dLCJ3IjpbIlwiQVwiIiwiXCJDXCIiLCJcIkJcIiIsIlwiQlwiIiwiXCJBXCIiLCJcIkZcIiIsIlwiQ1wiIiwiXCJBXCIiXSwicGFyIjp7InAiOjIwLCJzIjo4MH19">Open this lab in a new tab</a></p>
<hr />
<h2>Trap 2: <code>&gt;</code> vs <code>&gt;=</code> at the boundary</h2>
<pre><code class="language-js">function shipping(order) {
  if (order &gt; 50) {
    return 0;
  }
  return 5;
}

shipping(50);
</code></pre>
<p>The rule is "orders of 50 or more ship free."</p>
<p><strong>Predict which path runs.</strong> What does <code>shipping(50)</code> return? What about <code>49</code> and <code>51</code>?</p>
<p><strong>What happens.</strong> <code>shipping(50)</code> returns <code>5</code>, but it should return <code>0</code>. <code>50 &gt; 50</code> is false, so the order falls through to the <code>5</code>.</p>
<table>
<thead>
<tr>
<th><code>order</code></th>
<th>with <code>&gt;</code></th>
<th>with <code>&gt;=</code></th>
</tr>
</thead>
<tbody><tr>
<td>49</td>
<td>5</td>
<td>5</td>
</tr>
<tr>
<td><strong>50</strong></td>
<td><strong>5</strong></td>
<td><strong>0</strong></td>
</tr>
<tr>
<td>51</td>
<td>0</td>
<td>0</td>
</tr>
</tbody></table>
<p>Only the middle row differs, which is why this bug survives casual testing: <code>49</code> and <code>51</code> both look right.</p>
<p><strong>The mental model.</strong> Boundary bugs only show up <em>on</em> the boundary. Whenever a rule has a number in it, test three values: just below it, exactly on it, just above it. And translate the English into operators deliberately:</p>
<table>
<thead>
<tr>
<th>The rule says</th>
<th>Write</th>
</tr>
</thead>
<tbody><tr>
<td>"at least 50", "50 or more"</td>
<td><code>&gt;= 50</code></td>
</tr>
<tr>
<td>"more than 50", "over 50"</td>
<td><code>&gt; 50</code></td>
</tr>
<tr>
<td>"at most 50", "up to and including 50"</td>
<td><code>&lt;= 50</code></td>
</tr>
<tr>
<td>"under 50", "less than 50"</td>
<td><code>&lt; 50</code></td>
</tr>
</tbody></table>
<p><strong>Lab: fix <code>shipping</code>.</strong> Case 1 is the boundary itself.</p>
<iframe width="100%" height="680" style="border:0;max-width:100%"></iframe>

<p><a href="https://iineman2.github.io/code-glyphs/#e=eyJ2IjoxLCJrIjoiZml4IiwidCI6IkZyZWUgc2hpcHBpbmcgZnJvbSA1MCB1cCIsInAiOiJvcmRlciBpcyB0aGUgYmFza2V0IHRvdGFsIGluIHdob2xlIGRvbGxhcnMuIEFuIG9yZGVyIG9mIDUwIG9yIG1vcmUgc2hpcHMgZnJlZSAoc2hpcHBpbmcgaXMgMCk7IGFueXRoaW5nIHVuZGVyIDUwIHBheXMgNS4gRml4IHRoZSBzaGFwZS4gRm9yIG9yZGVyID0gNTAgdGhhdCBpcyAwLiIsImZuIjoic2hpcHBpbmciLCJhIjpbIm9yZGVyIl0sInMiOiJmdW5jdGlvbiBzaGlwcGluZyhvcmRlcikge1xuICBpZiAob3JkZXIgPiA1MCkge1xuICAgIHJldHVybiAwO1xuICB9XG4gIHJldHVybiA1O1xufVxuIiwiYyI6W1siNTAiXSxbIjMwIl1dLCJoIjpbWyI0OSJdLFsiNTEiXSxbIjEyMCJdLFsiMCJdXSwidyI6WyIwIiwiNSIsIjUiLCIwIiwiMCIsIjUiXSwicGFyIjp7InAiOjgsInMiOjM2fX0">Open this lab in a new tab</a></p>
<hr />
<h2>Trap 3: <code>&amp;&amp;</code> vs <code>||</code>, and negating a compound condition</h2>
<pre><code class="language-js">function unsafe(temp) {
  if (temp &lt; 5 &amp;&amp; temp &gt; 30) {
    return true;
  }
  return false;
}

unsafe(2);
</code></pre>
<p>The safe range is 5 to 30 inclusive, and <code>unsafe</code> should say whether <code>temp</code> is <em>outside</em> it.</p>
<p><strong>Predict which path runs.</strong> What does <code>unsafe(2)</code> return? Is there <em>any</em> number for which it returns <code>true</code>?</p>
<p><strong>What happens.</strong> <code>unsafe(2)</code> returns <code>false</code>, but the answer should be <code>true</code>. <code>2 &lt; 5</code> is true, but <code>2 &gt; 30</code> is false, so <code>&amp;&amp;</code> fails. And there is no such number: nothing is both below 5 and above 30, so the function returns <code>false</code> for every input.</p>
<p><strong>The mental model.</strong></p>
<ul>
<li><code>A &amp;&amp; B</code> means <strong>both</strong> must hold. It only ever <em>narrows</em> the set of inputs that get in.</li>
<li><code>A || B</code> means <strong>either</strong> may hold. It <em>widens</em> the set.</li>
</ul>
<p>"Outside the range" means "too low <em>or</em> too high": two ways in, so <code>||</code>. The mirror bug is just as common. If you write the <em>inside</em> check as <code>temp &gt;= 5 || temp &lt;= 30</code>, it is true for every number, because every number is at least 5 or at most 30.</p>
<p>When you negate a compound condition, the operator flips and each part is negated (De Morgan's laws):</p>
<pre><code class="language-js">!(a &amp;&amp; b)  ===  !a || !b
!(a || b)  ===  !a &amp;&amp; !b
</code></pre>
<p>Here it is checked on every combination of <code>a</code> and <code>b</code>:</p>
<table>
<thead>
<tr>
<th><code>a</code></th>
<th><code>b</code></th>
<th><code>!(a &amp;&amp; b)</code></th>
<th><code>!a || !b</code></th>
<th><code>!a &amp;&amp; !b</code></th>
</tr>
</thead>
<tbody><tr>
<td>true</td>
<td>true</td>
<td>false</td>
<td>false</td>
<td>false</td>
</tr>
<tr>
<td>true</td>
<td>false</td>
<td>true</td>
<td>true</td>
<td>false</td>
</tr>
<tr>
<td>false</td>
<td>true</td>
<td>true</td>
<td>true</td>
<td>false</td>
</tr>
<tr>
<td>false</td>
<td>false</td>
<td>true</td>
<td>true</td>
<td>true</td>
</tr>
</tbody></table>
<p>The third column always matches the fourth, never the fifth. So <code>!(temp &gt;= 5 &amp;&amp; temp &lt;= 30)</code> is the same as <code>temp &lt; 5 || temp &gt; 30</code>. I checked it for every whole number from -10 to 50. A common slip is to negate the parts but forget to flip <code>&amp;&amp;</code> into <code>||</code>.</p>
<p><strong>Lab: fix <code>unsafe</code>.</strong> Hidden cases sit right on the edges (5 and 30), so trap 2 is waiting there too.</p>
<iframe width="100%" height="680" style="border:0;max-width:100%"></iframe>

<p><a href="https://iineman2.github.io/code-glyphs/#e=eyJ2IjoxLCJrIjoiZml4IiwidCI6Ik91dHNpZGUgdGhlIHNhZmUgcmFuZ2UiLCJwIjoidGVtcCBpcyBhIHdob2xlIG51bWJlci4gVGhlIHNhZmUgcmFuZ2UgaXMgNSB0byAzMCwgYm90aCBlbmRzIGluY2x1ZGVkLiBGaXggdGhlIHNoYXBlIHNvIGl0IGxlYXZlcyB3aXRoIHRydWUgd2hlbiB0ZW1wIGlzIG91dHNpZGUgdGhlIHNhZmUgcmFuZ2UsIGFuZCBmYWxzZSB3aGVuIGl0IGlzIGluc2lkZS4gRm9yIHRlbXAgPSAyIHRoYXQgaXMgdHJ1ZS4iLCJmbiI6InVuc2FmZSIsImEiOlsidGVtcCJdLCJzIjoiZnVuY3Rpb24gdW5zYWZlKHRlbXApIHtcbiAgaWYgKHRlbXAgPCA1ICYmIHRlbXAgPiAzMCkge1xuICAgIHJldHVybiB0cnVlO1xuICB9XG4gIHJldHVybiBmYWxzZTtcbn1cbiIsImMiOltbIjIiXSxbIjE4Il1dLCJoIjpbWyIzMSJdLFsiNCJdLFsiNSJdLFsiMzAiXSxbIi0xMCJdXSwidyI6WyJ0cnVlIiwiZmFsc2UiLCJ0cnVlIiwidHJ1ZSIsImZhbHNlIiwiZmFsc2UiLCJ0cnVlIl0sInBhciI6eyJwIjoxMiwicyI6NjF9fQ">Open this lab in a new tab</a></p>
<hr />
<h2>Trap 4: No fallback branch (and nested ternaries)</h2>
<pre><code class="language-js">function sizeLabel(cm) {
  if (cm &lt; 10) {
    return "small";
  } else if (cm &lt; 20) {
    return "medium";
  } else if (cm &lt; 30) {
    return "large";
  }
}

sizeLabel(45);
</code></pre>
<p><strong>Predict which path runs.</strong> Which <code>return</code> line runs for <code>cm = 45</code>? What does the function hand back?</p>
<p><strong>What happens.</strong> None of them. All three conditions are false, the chain ends, and a function that finishes without hitting a <code>return</code> gives back <code>undefined</code>. Expected: <code>"xl"</code>.</p>
<p><strong>The mental model.</strong> An <code>if / else if</code> chain with no final <code>else</code> has a hidden branch: "nothing matched, do nothing". Ask of every chain, <em>what happens when none of the conditions is true?</em> If the honest answer is "that can't happen", write the <code>else</code> anyway and make it return something loud or obviously wrong. A silent <code>undefined</code> travels a long way before it breaks something.</p>
<p>Nested ternaries make the same chain shorter, and syntax forces you to write the last <code>else</code>:</p>
<pre><code class="language-js">const label = cm &lt; 10 ? "small"
            : cm &lt; 20 ? "medium"
            : cm &lt; 30 ? "large"
            : "xl";
</code></pre>
<p>That version is fine when each line is a plain value. Two ways it goes wrong:</p>
<ul>
<li><p><strong>Precedence.</strong> Ternary binds more loosely than <code>+</code> and <code>===</code>. This line is meant to print "Found 1 item", but</p>
<pre><code class="language-js">"Found " + count + count === 1 ? " item" : " items"
</code></pre>
<p>is parsed as <code>("Found " + count + count === 1) ? " item" : " items"</code>. The text before <code>?</code> is a string compared to <code>1</code>, which is never true, so the result for <code>count = 1</code> is just <code>" items"</code>: the "Found" part is gone as well. Wrap the ternary in parentheses: <code>"Found " + count + (count === 1 ? " item" : " items")</code> gives <code>"Found 1 item"</code>.</p>
</li>
<li><p><strong>Readability.</strong> Once a branch needs more than a value, switch back to <code>if / else</code>.</p>
</li>
</ul>
<p><strong>Lab: fix <code>sizeLabel</code>.</strong> Step through <code>sizeLabel(45)</code> and watch the function reach the closing brace without returning.</p>
<iframe width="100%" height="680" style="border:0;max-width:100%"></iframe>

<p><a href="https://iineman2.github.io/code-glyphs/#e=eyJ2IjoxLCJrIjoiZml4IiwidCI6IlNpemUgbGFiZWwgd2l0aCBhIGZhbGxiYWNrIiwicCI6ImNtIGlzIGEgbGVuZ3RoIGluIHdob2xlIGNlbnRpbWV0cmVzLiBGaXggdGhlIHNoYXBlIHNvIGl0IGxlYXZlcyB3aXRoIFwic21hbGxcIiB1bmRlciAxMCwgXCJtZWRpdW1cIiB1bmRlciAyMCwgXCJsYXJnZVwiIHVuZGVyIDMwLCBhbmQgXCJ4bFwiIGZvciBldmVyeXRoaW5nIGVsc2UuIEZvciBjbSA9IDQ1IHRoYXQgaXMgXCJ4bFwiLiIsImZuIjoic2l6ZUxhYmVsIiwiYSI6WyJjbSJdLCJzIjoiZnVuY3Rpb24gc2l6ZUxhYmVsKGNtKSB7XG4gIGlmIChjbSA8IDEwKSB7XG4gICAgcmV0dXJuIFwic21hbGxcIjtcbiAgfSBlbHNlIGlmIChjbSA8IDIwKSB7XG4gICAgcmV0dXJuIFwibWVkaXVtXCI7XG4gIH0gZWxzZSBpZiAoY20gPCAzMCkge1xuICAgIHJldHVybiBcImxhcmdlXCI7XG4gIH1cbn1cbiIsImMiOltbIjQ1Il0sWyI1Il1dLCJoIjpbWyIxMCJdLFsiMjUiXSxbIjMwIl0sWyIxOSJdLFsiOSJdXSwidyI6WyJcInhsXCIiLCJcInNtYWxsXCIiLCJcIm1lZGl1bVwiIiwiXCJsYXJnZVwiIiwiXCJ4bFwiIiwiXCJtZWRpdW1cIiIsIlwic21hbGxcIiJdLCJwYXIiOnsicCI6MjAsInMiOjc0fX0">Open this lab in a new tab</a></p>
<hr />
<h2>Practice: call the gate</h2>
<p>Two read-only puzzles from the free tier. You don't write any code. The run pauses at a gate (an <code>if</code> or loop condition), and you call whether it answers yes or no. Work out the values on paper first.</p>
<p><strong>Call the gate: first height over 5</strong></p>
<iframe width="100%" height="680" style="border:0;max-width:100%"></iframe>

<p><a href="https://iineman2.github.io/code-glyphs/?pz=P-dc7oz5">Open this puzzle in a new tab</a></p>
<p><strong>Call the gate: gold, silver or bronze</strong></p>
<iframe width="100%" height="680" style="border:0;max-width:100%"></iframe>

<p><a href="https://iineman2.github.io/code-glyphs/?pz=P-jpts57">Open this puzzle in a new tab</a></p>
<hr />
<h2>A 60-second branch review</h2>
<p>For any <code>if</code> chain, pick one concrete input and answer these:</p>
<ol>
<li>Which condition is checked first, and is it the narrowest one?</li>
<li>Do the boundary values (just below, on, just above) each land where the rule says?</li>
<li>In every <code>&amp;&amp;</code> / <code>||</code>, would I get the same answer if I read it aloud in plain English?</li>
<li>If I negated a compound condition, did the operator flip?</li>
<li>What happens when none of the branches match?</li>
</ol>
<p>Then step through it once with the input that worries you most. The wrong branch is usually visible in the first gate.</p>
]]></content:encoded></item><item><title><![CDATA[5 JavaScript Loop Bugs Every Beginner Hits (And How to Watch Them Happen)]]></title><description><![CDATA[Most loop bugs don't crash. They hand back a number that is slightly wrong, and the code looks fine when you read it top to bottom. Reading loops like…]]></description><link>https://codeglyphs.hashnode.dev/5-javascript-loop-bugs-every-beginner-hits-and-how-to-watch-them-happen</link><guid isPermaLink="true">https://codeglyphs.hashnode.dev/5-javascript-loop-bugs-every-beginner-hits-and-how-to-watch-them-happen</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[programming]]></category><dc:creator><![CDATA[Iineman2]]></dc:creator><pubDate>Wed, 02 Dec 2026 10:57:45 GMT</pubDate><content:encoded><![CDATA[<p>Most loop bugs don't crash. They hand back a number that is slightly wrong, and the code looks fine when you read it top to bottom.</p>
<p>Reading loops like prose is the problem. A loop is a small machine: some variables, a question asked before every turn, and a few lines that change the variables. If you keep a little table of those variables and update it line by line, the bug usually shows up on its own.</p>
<p>This post covers five bugs I see over and over in beginner code. Each one has:</p>
<ol>
<li>a short snippet with the bug,</li>
<li>a <strong>Predict before running</strong> prompt (do it on paper, it takes a minute),</li>
<li>the mental model that explains it,</li>
<li>a lab: the broken function, opened in a step-through visualizer, where you fix it and get checked against hidden cases.</li>
</ol>
<p>The labs use <a href="https://iineman2.github.io/code-glyphs/">Code Glyphs</a>, a browser step-through tool I built. You don't need it to follow along: every snippet below is plain JavaScript you can paste into Node or the browser console. But watching the variables change one step at a time is the fastest way I know to build the habit.</p>
<p><strong>How the labs work.</strong> Each lab opens with the broken function already loaded. Press <strong>Step</strong> to advance one stroke at a time and watch the values change, or <strong>Run</strong> to go straight to the result. Edit the shape (or the JavaScript pane), then press <strong>Check my shape</strong>. 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" and loops "rings". It's the same thing you already know.</p>
<p>If the embedded labs don't load where you're reading this, every lab also has a plain link right under it.</p>
<hr />
<h2>Bug 1: Off by one, the loop stops an item early</h2>
<pre><code class="language-js">function total(prices) {
  let sum = 0;
  for (let i = 0; i &lt; prices.length - 1; i += 1) {
    sum += prices[i];
  }
  return sum;
}

total([4, 8, 15]);
</code></pre>
<p><strong>Predict before running.</strong> Write down <code>i</code> and <code>sum</code> after every turn. What does <code>total([4, 8, 15])</code> return? What should it return?</p>
<p><strong>What happens.</strong> It returns <code>12</code>, not <code>27</code>. The list has 3 items, so <code>prices.length - 1</code> is 2, and the condition <code>i &lt; 2</code> lets <code>i</code> be 0 and 1 only. Index 2 (the <code>15</code>) is never visited.</p>
<p><strong>The mental model.</strong> A loop condition is a question asked <em>before every turn</em>: "may I take another turn?" To visit every item, the last turn must be the one where <code>i</code> is <code>length - 1</code>, and the first refusal must be <code>i === length</code>. So the question is <code>i &lt; prices.length</code>.</p>
<p>Off-by-one bugs come in three flavours, and all three are the same mistake about where the fence ends:</p>
<table>
<thead>
<tr>
<th>You wrote</th>
<th>What it does on <code>[4, 8, 15]</code></th>
</tr>
</thead>
<tbody><tr>
<td><code>i &lt; prices.length - 1</code></td>
<td>skips the last item, returns <code>12</code></td>
</tr>
<tr>
<td><code>i &lt;= prices.length</code></td>
<td>reads <code>prices[3]</code>, which is <code>undefined</code>, so the sum becomes <code>NaN</code></td>
</tr>
<tr>
<td><code>for (let i = 1; i &lt; n; i += 1)</code> to add <code>1..n</code></td>
<td>never adds <code>n</code>: <code>n = 4</code> gives <code>6</code>, not <code>10</code></td>
</tr>
</tbody></table>
<p>A quick check that works for all of them: take the smallest case that matters (a list of 1 item, or <code>n = 1</code>) and ask "which <code>i</code> values run?" out loud.</p>
<p><strong>Lab: fix <code>total</code>.</strong> The starting shape is the code above. Case 1 is the list you just traced.</p>
<iframe width="100%" height="680" style="border:0;max-width:100%"></iframe>

<p><a href="https://iineman2.github.io/code-glyphs/#e=eyJ2IjoxLCJrIjoiZml4IiwidCI6IkFkZCB1cCBldmVyeSBwcmljZSIsInAiOiJwcmljZXMgaXMgYSBsaXN0IG9mIHdob2xlIG51bWJlcnMuIEZpeCB0aGUgc2hhcGUgc28gaXQgbGVhdmVzIHdpdGggdGhlIHN1bSBvZiBhbGwgdGhlIHByaWNlcywgdGhlIGxhc3Qgb25lIGluY2x1ZGVkLiBGb3IgcHJpY2VzID0gWzQsIDgsIDE1XSB0aGF0IGlzIDI3LiIsImZuIjoidG90YWwiLCJhIjpbInByaWNlcyJdLCJzIjoiZnVuY3Rpb24gdG90YWwocHJpY2VzKSB7XG4gIGxldCBzdW0gPSAwO1xuICBmb3IgKGxldCBpID0gMDsgaSA8IHByaWNlcy5sZW5ndGggLSAxOyBpICs9IDEpIHtcbiAgICBzdW0gKz0gcHJpY2VzW2ldO1xuICB9XG4gIHJldHVybiBzdW07XG59XG4iLCJjIjpbWyJbNCwgOCwgMTVdIl0sWyJbXSJdXSwiaCI6W1siWzEwLCAyMF0iXSxbIls3XSJdLFsiWzMsIDMsIDMsIDNdIl0sWyJbMTAwLCAtNTAsIDI1XSJdXSwidyI6WyIyNyIsIjAiLCIzMCIsIjciLCIxMiIsIjc1Il0sInBhciI6eyJwIjoxOSwicyI6MTk2fX0">Open this lab in a new tab</a></p>
<hr />
<h2>Bug 2: Overwriting an accumulator (<code>=</code> instead of <code>+=</code>)</h2>
<pre><code class="language-js">function sumPositive(nums) {
  let total = 0;
  for (const n of nums) {
    if (n &gt; 0) {
      total = n;
    }
  }
  return total;
}

sumPositive([3, -1, 4, 2]);
</code></pre>
<p><strong>Predict before running.</strong> Track <code>total</code> for each item of <code>[3, -1, 4, 2]</code>. What comes back?</p>
<p><strong>What happens.</strong> <code>2</code>: the last positive number. <code>total = n</code> doesn't add anything, it <em>replaces</em> the old value with the current item, every time. The correct answer is <code>9</code>.</p>
<p><strong>The mental model.</strong> An accumulator has to read itself. <code>total += n</code> means <code>total = total + n</code>: the right-hand side uses the old value. When you review a loop that builds up a result, ask one question of the line that updates it: <em>does the right-hand side mention the variable on the left?</em> If not, you are replacing, not accumulating.</p>
<p>The same bug has a cousin: writing <code>let total = 0</code> <em>inside</em> the loop body. That creates a fresh <code>total</code> on every turn, so each pass starts from zero again. Declare accumulators before the loop, update them inside.</p>
<p>Also notice how this one hides. For <code>[-5, -2]</code> the broken version returns <code>0</code>, which happens to be right. A test with a single example can pass while the bug is still there.</p>
<p><strong>Lab: fix <code>sumPositive</code>.</strong></p>
<iframe width="100%" height="680" style="border:0;max-width:100%"></iframe>

<p><a href="https://iineman2.github.io/code-glyphs/#e=eyJ2IjoxLCJrIjoiZml4IiwidCI6IkFkZCB1cCB0aGUgcG9zaXRpdmUgbnVtYmVycyIsInAiOiJudW1zIGlzIGEgbGlzdCBvZiB3aG9sZSBudW1iZXJzLiBGaXggdGhlIHNoYXBlIHNvIGl0IGxlYXZlcyB3aXRoIHRoZSBzdW0gb2YgdGhlIG51bWJlcnMgdGhhdCBhcmUgYWJvdmUgMCAobmVnYXRpdmVzIGFuZCB6ZXJvIGFyZSBza2lwcGVkKS4gRm9yIG51bXMgPSBbMywgLTEsIDQsIDJdIHRoYXQgaXMgOS4iLCJmbiI6InN1bVBvc2l0aXZlIiwiYSI6WyJudW1zIl0sInMiOiJmdW5jdGlvbiBzdW1Qb3NpdGl2ZShudW1zKSB7XG4gIGxldCB0b3RhbCA9IDA7XG4gIGZvciAoY29uc3QgbiBvZiBudW1zKSB7XG4gICAgaWYgKG4gPiAwKSB7XG4gICAgICB0b3RhbCA9IG47XG4gICAgfVxuICB9XG4gIHJldHVybiB0b3RhbDtcbn1cbiIsImMiOltbIlszLCAtMSwgNCwgMl0iXSxbIlstNSwgLTJdIl1dLCJoIjpbWyJbMTBdIl0sWyJbMSwgMiwgM10iXSxbIlswLCA3LCAtMywgOF0iXSxbIlstMSwgNSwgLTIsIDYsIDldIl1dLCJ3IjpbIjkiLCIwIiwiMTAiLCI2IiwiMTUiLCIyMCJdLCJwYXIiOnsicCI6MTMsInMiOjE1NX19">Open this lab in a new tab</a></p>
<hr />
<h2>Bug 3: Returning too early</h2>
<pre><code class="language-js">function allPass(scores) {
  for (const s of scores) {
    if (s &gt;= 60) {
      return true;
    } else {
      return false;
    }
  }
  return true;
}

allPass([80, 45, 90]);
</code></pre>
<p><strong>Predict before running.</strong> How many items does the loop look at before the function ends? What does <code>allPass([80, 45, 90])</code> return?</p>
<p><strong>What happens.</strong> It looks at exactly one item. <code>80</code> passes, so it returns <code>true</code> and the function is over. The <code>45</code> is never examined. (Swap the first score for a failing one and it returns <code>false</code> just as quickly, so the answer depends only on the first item.) Expected: <code>false</code>.</p>
<p><strong>The mental model.</strong> <code>return</code> ends the whole function, not just the current turn. Inside a loop, every <code>return</code> is a claim: "I now know the final answer." So before writing it, ask whether <em>this one item</em> really settles the question.</p>
<p>For "do all items pass?", the answer is:</p>
<ul>
<li>one failure settles it (<code>return false</code> inside the loop),</li>
<li>one success settles nothing (you have to see the rest),</li>
<li>so <code>return true</code> goes <em>after</em> the loop.</li>
</ul>
<p>The pattern flips for "does any item fail?", and it's the same shape for "find the first match":</p>
<table>
<thead>
<tr>
<th>Question</th>
<th>Settled early by</th>
<th>After the loop</th>
</tr>
</thead>
<tbody><tr>
<td>Do all items pass?</td>
<td>the first failure, <code>return false</code></td>
<td><code>return true</code></td>
</tr>
<tr>
<td>Does any item fail?</td>
<td>the first failure, <code>return true</code></td>
<td><code>return false</code></td>
</tr>
<tr>
<td>Find the first item that matches</td>
<td>the first match, <code>return item</code></td>
<td>"not found" value</td>
</tr>
</tbody></table>
<p>An <code>if</code> with a <code>return</code> in both branches inside a loop body is almost always this bug.</p>
<p><strong>Lab: fix <code>allPass</code>.</strong> Watch how few steps the broken version takes, then compare with your fix.</p>
<iframe width="100%" height="680" style="border:0;max-width:100%"></iframe>

<p><a href="https://iineman2.github.io/code-glyphs/#e=eyJ2IjoxLCJrIjoiZml4IiwidCI6IkRpZCBldmVyeSBzY29yZSBwYXNzPyIsInAiOiJzY29yZXMgaXMgYSBsaXN0IG9mIG1hcmtzLCBhbmQgNjAgb3IgbW9yZSBwYXNzZXMuIEZpeCB0aGUgc2hhcGUgc28gaXQgbGVhdmVzIHdpdGggdHJ1ZSBvbmx5IHdoZW4gZXZlcnkgbWFyayBwYXNzZXMsIGFuZCBmYWxzZSBpZiBldmVuIG9uZSBkb2VzIG5vdC4gQW4gZW1wdHkgbGlzdCBwYXNzZXMuIEZvciBzY29yZXMgPSBbODAsIDQ1LCA5MF0gdGhhdCBpcyBmYWxzZS4iLCJmbiI6ImFsbFBhc3MiLCJhIjpbInNjb3JlcyJdLCJzIjoiZnVuY3Rpb24gYWxsUGFzcyhzY29yZXMpIHtcbiAgZm9yIChjb25zdCBzIG9mIHNjb3Jlcykge1xuICAgIGlmIChzID49IDYwKSB7XG4gICAgICByZXR1cm4gdHJ1ZTtcbiAgICB9IGVsc2Uge1xuICAgICAgcmV0dXJuIGZhbHNlO1xuICAgIH1cbiAgfVxuICByZXR1cm4gdHJ1ZTtcbn1cbiIsImMiOltbIls4MCwgNDUsIDkwXSJdLFsiWzcwLCA2NSwgOTBdIl1dLCJoIjpbWyJbNTUsIDgwXSJdLFsiWzYwXSJdLFsiWzkwLCA1OV0iXSxbIltdIl0sWyJbNzUsIDYxLCA0MCwgOTldIl1dLCJ3IjpbImZhbHNlIiwidHJ1ZSIsImZhbHNlIiwidHJ1ZSIsImZhbHNlIiwidHJ1ZSIsImZhbHNlIl0sInBhciI6eyJwIjoxMCwicyI6ODh9fQ">Open this lab in a new tab</a></p>
<hr />
<h2>Bug 4: Starting <code>min</code> or <code>max</code> at 0</h2>
<pre><code class="language-js">function largest(temps) {
  let max = 0;
  for (const t of temps) {
    if (t &gt; max) {
      max = t;
    }
  }
  return max;
}

largest([-4, -9, -2]);
</code></pre>
<p><strong>Predict before running.</strong> Run it by hand on <code>[-4, -9, -2]</code>, then on <code>[3, 8, 5]</code>. Do both come out right?</p>
<p><strong>What happens.</strong> <code>[3, 8, 5]</code> gives <code>8</code>, which is correct, so the function looks fine on the first thing you try. <code>[-4, -9, -2]</code> gives <code>0</code> instead of <code>-2</code>. No item is bigger than <code>0</code>, so <code>max</code> never changes and the <code>0</code> you invented is returned. It isn't even in the list.</p>
<p>The mirror image: <code>let min = 0</code> on <code>[7, 12, 9]</code> returns <code>0</code>, a value that was never in the data.</p>
<p><strong>The mental model.</strong> The starting value of an accumulator must be one that can't affect the result. For a sum that's <code>0</code>, for a product it's <code>1</code>. For "biggest so far" there is no such number in the data, because any number you pick (like 0) can win against the real items. The safe start is an actual item: <code>let max = temps[0]</code>.</p>
<p>(In plain JavaScript you can also start at <code>-Infinity</code>, or use <code>Math.max(...temps)</code>. The lab asks for the first-item version, and its checker rejects <code>Infinity</code>, because it only accepts plain pieces.)</p>
<p>Decide what an empty list means <em>before</em> you write this. <code>temps[0]</code> on <code>[]</code> is <code>undefined</code>, and that might be exactly the answer you want, or a bug to handle.</p>
<p><strong>Lab: fix <code>largest</code>.</strong></p>
<iframe width="100%" height="680" style="border:0;max-width:100%"></iframe>

<p><a href="https://iineman2.github.io/code-glyphs/#e=eyJ2IjoxLCJrIjoiZml4IiwidCI6Ildhcm1lc3QgZGF5LCBldmVuIGluIHdpbnRlciIsInAiOiJ0ZW1wcyBpcyBhIGxpc3Qgb2YgdGVtcGVyYXR1cmVzIGluIGRlZ3JlZXMsIGFuZCB0aGV5IGNhbiBiZSBiZWxvdyB6ZXJvLiBGaXggdGhlIHNoYXBlIHNvIGl0IGxlYXZlcyB3aXRoIHRoZSBoaWdoZXN0IG9uZS4gRm9yIHRlbXBzID0gWy00LCAtOSwgLTJdIHRoYXQgaXMgLTIuIiwiZm4iOiJsYXJnZXN0IiwiYSI6WyJ0ZW1wcyJdLCJzIjoiZnVuY3Rpb24gbGFyZ2VzdCh0ZW1wcykge1xuICBsZXQgbWF4ID0gMDtcbiAgZm9yIChjb25zdCB0IG9mIHRlbXBzKSB7XG4gICAgaWYgKHQgPiBtYXgpIHtcbiAgICAgIG1heCA9IHQ7XG4gICAgfVxuICB9XG4gIHJldHVybiBtYXg7XG59XG4iLCJjIjpbWyJbLTQsIC05LCAtMl0iXSxbIlszLCA4LCA1XSJdXSwiaCI6W1siWy0xXSJdLFsiWy03LCAtMywgLTEyXSJdLFsiWzAsIDZdIl0sWyJbLTIsIDQsIC05XSJdXSwidyI6WyItMiIsIjgiLCItMSIsIi0zIiwiNiIsIjQiXSwicGFyIjp7InAiOjE1LCJzIjoxMzN9fQ">Open this lab in a new tab</a></p>
<hr />
<h2>Bug 5: A condition that never allows a turn (or never stops)</h2>
<pre><code class="language-js">function sumDown(n) {
  let total = 0;
  let i = n;
  while (i &lt; 1) {
    total += i;
    i -= 1;
  }
  return total;
}

sumDown(4);
</code></pre>
<p><strong>Predict before running.</strong> How many times does the loop body run for <code>n = 4</code>? What comes back?</p>
<p><strong>What happens.</strong> Zero turns, and it returns <code>0</code>. The condition is checked <em>before</em> the first turn: <code>i</code> starts at 4, <code>4 &lt; 1</code> is false, and the loop is skipped entirely. Expected: <code>10</code>.</p>
<p><strong>The mental model.</strong> A <code>while</code> loop needs three things to agree:</p>
<ol>
<li>a <strong>start</strong> value,</li>
<li>a <strong>condition</strong> that is true while there is work left,</li>
<li>a <strong>step</strong> that moves toward making the condition false.</li>
</ol>
<p>Two ways to break that agreement:</p>
<ul>
<li>the condition is false at the start, so the body runs <strong>zero times</strong> (this lab),</li>
<li>the step moves <em>away</em> from making it false, so the loop <strong>never ends</strong>.</li>
</ul>
<p>Both can come from the same one-character mistake. Try this: in the broken <code>sumDown</code>, give it <code>n = 0</code>. Now <code>i</code> starts at 0, <code>0 &lt; 1</code> is true, and each turn makes <code>i</code> smaller, which keeps it below 1 forever. The lab's interpreter stops it with <em>"This ring never ends. Stopped after 300,000 steps"</em>. In a real browser tab or Node process there is no such safety net, so don't run an unfinished <code>while</code> loop in the console unprepared.</p>
<p>Checklist for any <code>while</code>: <em>Is the condition true on the first check? Does every turn push it closer to false?</em> Say it out loud with the real numbers.</p>
<p><strong>Lab: fix <code>sumDown</code>.</strong> Step through <code>sumDown(4)</code> and watch the loop get skipped. Then step through the same shape with <code>n = 0</code> in the Run panel to see it run away.</p>
<iframe width="100%" height="680" style="border:0;max-width:100%"></iframe>

<p><a href="https://iineman2.github.io/code-glyphs/#e=eyJ2IjoxLCJrIjoiZml4IiwidCI6IkNvdW50IGRvd24gYW5kIGFkZCIsInAiOiJuIGlzIGEgd2hvbGUgbnVtYmVyLCAwIG9yIG1vcmUuIEZpeCB0aGUgc2hhcGUgc28gaXQgbGVhdmVzIHdpdGggbiArIChuIC0gMSkgKyAuLi4gKyAxIChhbmQgMCB3aGVuIG4gaXMgMCkuIEZvciBuID0gNCB0aGF0IGlzIDEwLiIsImZuIjoic3VtRG93biIsImEiOlsibiJdLCJzIjoiZnVuY3Rpb24gc3VtRG93bihuKSB7XG4gIGxldCB0b3RhbCA9IDA7XG4gIGxldCBpID0gbjtcbiAgd2hpbGUgKGkgPCAxKSB7XG4gICAgdG90YWwgKz0gaTtcbiAgICBpIC09IDE7XG4gIH1cbiAgcmV0dXJuIHRvdGFsO1xufVxuIiwiYyI6W1siNCJdLFsiMSJdXSwiaCI6W1siMCJdLFsiNiJdLFsiMTAiXSxbIjMiXV0sInciOlsiMTAiLCIxIiwiMCIsIjIxIiwiNTUiLCI2Il0sInBhciI6eyJwIjoxNiwicyI6MjI4fX0">Open this lab in a new tab</a></p>
<hr />
<h2>Practice: count the turns</h2>
<p>One more thing to try, a read-only puzzle from the free tier. You don't write any code: you predict how many times a loop body runs.</p>
<p><strong>Turns of the ring: sum from 1 by 1s, below height</strong>: read the condition carefully, count on paper, then answer.</p>
<iframe width="100%" height="680" style="border:0;max-width:100%"></iframe>

<p><a href="https://iineman2.github.io/code-glyphs/?pz=P-yqqshd">Open this puzzle in a new tab</a></p>
<hr />
<h2>A 60-second loop review</h2>
<p>Before you run a loop you wrote, take the smallest interesting input and answer these five questions on paper:</p>
<ol>
<li>Which values does the loop variable take? Is the first one included, the last one?</li>
<li>Does every line that builds up a result <em>read</em> the variable it updates?</li>
<li>Is each <code>return</code> inside the loop really settled by this one item?</li>
<li>Does the starting value of the result belong to the data, or can it win by accident?</li>
<li>Is the loop condition true on the first check, and does every turn move it toward false?</li>
</ol>
<p>If you want to share a lab with a student or a teammate, it's all in the link: the task, the cases and the starting code. Your fix is never part of it.</p>
]]></content:encoded></item></channel></rss>