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 edgeWatch 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); // NaNparseInt 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 mutationtoSorted, 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?
Keep reading
Related articles from the SudoSecurity blog.
Angular 18: Deferred Views & Built-in Control Flow
The newest release of Angular – which is Angular 18 – is planned to be released on May 22nd, 2024. This is Google's super popular TypeScript based webapp framework that allows developers to create amazing web applications. The features, changes, and goodies of this release are deferrable views…
Angular 15: Simplifies Development Promises
Angular 15, a planned upgrade to Google’s TypeScript framework for web development, will stabilize standalone component APIs, simplifying application building, and offer a new way to compose UI logic, the company announced. Angular 15 is expected to arrive in November, said Minko Gechev, Google…
Angular 14 is Now Released
Angular 14, the latest version of the Google-developed, TypeScript-based web application framework, has arrived, featuring typed forms and a developer preview of standalone components. Standalone components simplify the development of Angular applications by reducing the need for NgModules.…
Node Runs TypeScript Now. Here's Exactly What It Strips, What It Refuses, and What It Costs
Node 24 and 26 run .ts files with no build step and no flags, by replacing types with whitespace. I ran eleven test cases, the TypeScript 7 compiler and tsx against both versions: enums, parameter properties and type imports without the type keyword all break, type errors run anyway, and...