JavaScript Type Coercion: == vs === Explained
On this page
Learning Objective
Name JavaScript's primitive types and its object type, explain how typeof reports them, predict implicit type coercion in arithmetic, comparisons and conditions, choose between strict equality, loose equality and Object.is, and handle the quirks of numbers, null and undefined safely.
Concept Explanation
Every value in JavaScript is either a primitive or an object. There are seven primitives: string, number, bigint, boolean, undefined, symbol and null. Primitives are immutable: methods like toUpperCase return a new string rather than changing the original. Everything else is an object, including arrays, functions, dates, maps and regular expressions. The typeof operator reports the category, with two historical quirks that every developer must remember: typeof null returns "object", a bug kept for compatibility, and typeof a function returns "function" even though functions are objects. Array.isArray is the reliable test for arrays.
JavaScript converts values between types automatically in many places, which is called implicit coercion. The plus operator concatenates if either side is a string, so 1 + "2" is "12", while minus, times and divide convert both sides to numbers, so "5" - 2 is 3. Conditions convert values to booleans. Only a short list of values is falsy: false, 0, -0, 0n, the empty string, null, undefined and NaN. Everything else is truthy, including the string "0", the string "false", empty arrays and empty objects. Knowing that list prevents a whole class of bugs.
Equality comes in three forms. Strict equality, written with three equals signs, compares without coercion: values must have the same type and value. Loose equality, with two equals signs, coerces first using a complicated algorithm, so 0 == "" is true and null == undefined is true while null == 0 is false. Most style guides require strict equality, with one common exception: value == null is a concise check for null or undefined. Object.is behaves like strict equality except that it treats NaN as equal to itself and distinguishes 0 from -0, which matters in a few algorithms and is what React uses to decide whether state changed.
Numbers are IEEE 754 double precision floating point values. That gives you NaN, which is not equal to anything including itself, Infinity, and the famous 0.1 + 0.2 that is not exactly 0.3. Integers are exact only up to Number.MAX_SAFE_INTEGER, about nine quadrillion; beyond that, use BigInt, which is why database identifiers larger than that should be sent from APIs as strings. For money, avoid floating point arithmetic on decimal amounts: work in integer minor units such as cents, or use a decimal library, and format with Intl.NumberFormat.
Modern operators make absent values easier to handle. Optional chaining, a?.b?.c, stops and returns undefined if any link is null or undefined. Nullish coalescing, a ?? b, returns b only when a is null or undefined, unlike a || b, which also replaces 0, the empty string and false. The difference matters for settings where 0 or an empty string is a legitimate value.
| Expression | Result | Why |
|---|---|---|
| typeof null | "object" | Historical bug kept for compatibility |
| 1 + "2" | "12" | Plus concatenates if either side is a string |
| "5" - 2 | 3 | Minus converts both sides to numbers |
| [] == false | true | Loose equality coerces both to 0 |
| NaN === NaN | false | NaN is never equal to anything |
| Object.is(NaN, NaN) | true | SameValue comparison |
| 0.1 + 0.2 === 0.3 | false | Binary floating point rounding |
| 0 ?? 10 versus 0 or 10 | 0 versus 10 | ?? only replaces null and undefined |
Worked Example: Parsing Query Parameters Without Coercion Bugs
Values from the URL, forms and storage are always strings. This helper converts them deliberately instead of relying on implicit coercion.
const params = new URLSearchParams('?page=0&limit=&debug=false&price=19.99');
// Buggy: relies on truthiness and implicit coercion
const pageBad = params.get('page') || 1; // '0' is truthy, so this is '0', a string
const debugBad = Boolean(params.get('debug')); // 'false' is a non-empty string, so true
const totalBad = params.get('price') + 5; // '19.995' by string concatenation
// Deliberate conversions
function toInt(value, fallback) {
if (value === null || value.trim() === '') return fallback;
const n = Number(value);
return Number.isInteger(n) ? n : fallback; // rejects 'abc', '1.5', 'Infinity'
}
function toBool(value) {
return value === 'true' || value === '1';
}
function toCents(value) {
const n = Number(value);
return Number.isFinite(n) ? Math.round(n * 100) : null; // money as integer cents
}
const page = toInt(params.get('page'), 1); // 0, a legitimate page index here
const limit = toInt(params.get('limit'), 20); // 20, because the value was empty
const debug = toBool(params.get('debug')); // false
const totalCents = toCents(params.get('price')) + 500; // 2499
const settings = { volume: 0, label: '' };
console.log(settings.volume || 50, settings.volume ?? 50); // 50 0
console.log(settings.theme?.accent ?? 'purple'); // 'purple', no TypeError
console.log(new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' })
.format(totalCents / 100)); // $24.99The helper functions make each conversion's rules explicit, including what counts as missing. Using ?? keeps a deliberate volume of 0, while || would have overwritten it with the default.
Real-World Examples
- Twitter's API documentation advised developers to use the id_str field rather than the numeric id field for tweet identifiers, because 64-bit identifiers exceed Number.MAX_SAFE_INTEGER and are silently rounded when parsed as JavaScript numbers.
- Optional chaining and nullish coalescing were standardized in ECMAScript 2020 after TypeScript 3.7 added them in 2019, and they quickly replaced long chains of logical and checks and lodash get calls in many codebases.
Review Questions & Answers
false, 0, -0, 0n, the empty string, null, undefined and NaN. Every other value is truthy, including "0", "false", empty arrays and empty objects.
a || b returns b whenever a is falsy, so it replaces 0, the empty string and false as well as null and undefined. a ?? b returns b only when a is null or undefined, so legitimate falsy values are kept.
Numbers are binary floating point, and 0.1 and 0.2 cannot be represented exactly, so their sum is 0.30000000000000004. Money should be stored and calculated in integer minor units such as cents, or with a decimal library, and only formatted as decimals for display.
The common accepted case is value == null, which is true for both null and undefined and nothing else. In almost all other cases strict equality should be used, because loose equality's coercion rules produce surprising results.