Skip to content

Lesson 3 of 14 · 20m

Numbers, Coercion, and the sort() Trap

One double for every number, `==` coercion you can't memorize, and a `sort` that's stringly-typed and mutates in place.

[10, 9, 2, 21].sort() returns [10, 2, 21, 9]. Not a bug report — that's the spec. The default Array.prototype.sort converts every element to a string and compares lexicographically, so 2 beats 10 the same way "b" beats "a". JavaScript's number and coercion rules are a set of small, exactly-specified traps, and each one has a matching production incident.

Every number is a double

JavaScript has one number type: IEEE-754 double. Integers are exact only up to Number.MAX_SAFE_INTEGER — 2^53 − 1, or 9,007,199,254,740,991. Past that, 2**53 and 2**53 + 1 are the same number.

This is why Twitter's API ships id and id_str on every tweet object, and why Discord serializes snowflake IDs as strings: 64-bit IDs exceed 2^53, and any JavaScript consumer reading the numeric field gets a silently wrong integer — a different tweet, a different user, a wrong-row update. If an API gives you a big integer, keep it a string end-to-end.

0.1 + 0.2 === 0.30000000000000004. The standard fix isn't tolerance hacks; it's never doing fractional math on money at all. Store cents:

const totalCents = priceCents * quantity;          // integers, exact
const display = (totalCents / 100).toFixed(2);     // format at the edge

Watch toFixed anyway — (1.005).toFixed(2) is "1.00", because 1.005 is stored as 1.00499999…. Formatting is display-only; do arithmetic in integers or reach for a decimal library when cents aren't granular enough. BigInt (10n) is the answer for integers past 2^53 — it can't mix with Number, and JSON.stringify throws on it, which tells you something about JSON's own number problems.

parseInt forgives, Number judges, isNaN lies

parseInt('12abc');     // 12 — parses until it can't, then stops
Number('12abc');       // NaN — all-or-nothing conversion
Number('');            // 0 — yes, really
Number(null);          // 0
Number(undefined);     // NaN

parseInt is for extracting a number from a messy string ('42px'); it still wants its radix — parseInt(n, 10) — even though the octal trap of ES3 is long dead. Number() is the strict converter. And the global isNaN coerces first: isNaN('abc') is true, which told generations of code that strings aren't numbers. Number.isNaN is the honest check — Number.isNaN(NaN) and nothing else.

== has a coercion algorithm; you will not memorize it

'5' - 0 is 5 (string coerced to number), '5' + 0 is '50' (number coerced to string), [] == '' is true, null == undefined is true, and NaN == NaN is false. The == coercion table is a page of spec nobody has ever been glad they memorized. === skips it entirely. The only == idiom that survives code review is x == null matching both null and undefined — and x ?? y usually says it better.

sort mutates, too

Beyond the string comparator, sort() sorts in place — it returns the same array, mutated:

const sorted = [...nums].sort((a, b) => a - b);          // copy first
const sorted2 = nums.toSorted((a, b) => a - b);          // ES2023, no mutation

toSorted, toReversed, toSpliced, and with are the non-mutating copy methods (Node 20+, all modern browsers) — the ones to use when the array lives in React state or shared caches. For strings, localeCompare handles real alphabets; Intl.Collator is the tunable version.

The wrong mental model

The model that fails is "numbers behave like ints and floats in other languages." There is one double, one coercion engine under == and +, and a sort that's stringly-typed by default. The practice: === everywhere, Number.isSafeInteger on foreign integers, cents or BigInt for money and IDs, an explicit comparator on every sort, and toSorted anywhere mutation would corrupt shared state.

Try this

Sort [10, 9, 2, 21, 1, 100] three ways: default, (a, b) => a - b, and (a, b) => b - a. Then take the string '19' and compute '19' + 1, '19' - 1, Number('19') + 1, and parseInt('19abc', 10) — and explain to a teammate which of the four results surprised you and why it shouldn't have.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.