#19 · Types and comparisons

Find the bug · #19 · Types and comparisons Easy JavaScript

Version 1.10 is told to “update” to 1.9

The app’s update banner tells people on the newest version to update to an older one.

On this page

The report

Bug report

The app shows an “Update available” banner when a newer version is out. Since version 1.10 shipped, people on 1.10 are being told to update to 1.9.

The code

Read it first: what should it do? Then click the line where you think the bug is.

JavaScriptClick the line you think is wrong
// True if the installed app is older than the latest release.
function needsUpdate(installed, latest) {
  const a = installed.split('.');
  const b = latest.split('.');
  for (let i = 0; i < 3; i++) {
    if (a[i] < b[i]) return true;
    if (a[i] > b[i]) return false;
  }
  return false;
}

Read it, then pick a line.

What it prints

Running it on a small example prints the output on the left. It should print the output on the right.

The example
console.log(needsUpdate('1.8.0', '1.9.0'));
console.log(needsUpdate('1.10.0', '1.9.0'));

It prints

true
true

It should print

true
false
Show the answer: the bug, the fix, and how you’d find it

The bug (lines 3, 4)

Lines 3 and 4 split the versions into strings, so line 6 compares text, not numbers. Text compares character by character: "1" comes before "9", so "10" < "9" is true and 1.10 looks older than 1.9. Turn each part into a number first.

The fix

1// True if the installed app is older than the latest release.2function needsUpdate(installed, latest) {3  const a = installed.split('.');4  const b = latest.split('.');3  const a = installed.split('.').map(Number);4  const b = latest.split('.').map(Number);5  for (let i = 0; i < 3; i++) {6    if (a[i] < b[i]) return true;7    if (a[i] > b[i]) return false;

How you’d find it

  1. Reproduce with the reported pair: needsUpdate("1.10.0", "1.9.0") says true. Versions 1.8 against 1.9 work fine.
  2. So it only breaks when a part has two digits. That smells like text comparison. Check the types: split returns strings.
  3. Confirm it in the console: "10" < "9" is true, while 10 < 9 is false.

The test that catches it

It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.

assert.equal(needsUpdate('1.10.0', '1.9.0'), false);
assert.equal(needsUpdate('1.9.0', '1.10.0'), true);
assert.equal(needsUpdate('2.0.0', '2.0.0'), false);

Where else this bites

  • Sorting file names puts img10.png before img2.png.
  • Comparing ids or prices that arrived as strings from JSON or a form.
Your progress stays on this device.