JavaScript Types and Coercion Explained in Complete Depth
A field manual to JavaScript types: the seven primitives, objects, typeof, equality, truthiness and every coercion rule, with each bug and its fix.

Types are the first place JavaScript surprises people and the last place it stops surprising them. The language does not stop you from adding a string to a number, comparing an array with a boolean or reading a property of undefined. It converts, quietly, by rules that are precise and short, and the rules produce results that look random until you know them. This guide is the full set. It starts with the values themselves, the seven primitives and the object, then covers how the language names them with typeof, how it compares them, how it turns one into another and how the numeric and text types hold their data. After that it turns to practice: the bugs each rule causes, a catalogue of the fixes and the checks that belong at the edges of a program. Every example runs on Node.js 24 as an ES module, and the output shown is from the run. The related single-topic posts are linked where they apply, and the code is written to be pasted into a file and run.
The guide is arranged by what a reader needs when a type bug is in front of them. Read the section on the value you have, the section on the operator you used and the field manual at the end, in that order. The seven primitives are listed in the post on primitive types, and the object side is covered in the post on primitives versus objects.
Why the language converts at all
The conversions are not an accident of carelessness. JavaScript was designed in 1995 for small scripts inside web pages, where the input was text from a form, the output was text in a document and a script that stopped on every type mismatch would have stopped on every page. Converting quietly was a feature: a field holding "5" could be multiplied by a price without ceremony. The cost of that decision arrived later, as the programs grew and the quiet conversions became the source of bugs nobody could see in review. The language could not remove the conversions without breaking the web, so it added tools that opt out of them: strict equality, Number.isNaN, ??, optional chaining, BigInt with its refusal to mix, and Symbol with its refusal to convert. Reading the newer features as a series of "do not guess" switches is a good way to remember what each is for.
Two consequences follow for how you write code. First, the language will not tell you that a conversion happened, so the discipline has to come from conventions: convert at the boundary, compare strictly, write defaults with ??. Second, a tool outside the language is worth having. A linter catches the loose comparisons and the unsafe falsy checks, and a type checker catches the arithmetic on a string before the code runs. Neither replaces knowing the rules, because the checks stop at the edge of your own code, and the data that arrives from outside carries whatever types its author chose.
The type system in one page
JavaScript has two kinds of value. A primitive is a single immutable value: it has no properties of its own and no identity apart from its content. An object is a collection of properties reached through a reference, and it has identity: two objects with identical contents are different objects. There are seven primitive types and no others, and arrays, functions, dates, maps and class instances are all objects.
const samples = [
undefined,
null,
true,
42,
"text",
9007199254740993n,
Symbol("id"),
{ id: 1 },
[1, 2],
() => {},
new Date(0),
/x/,
new Map(),
class Order {},
];
for (const value of samples) {
const label = typeof value === "symbol" ? value.toString() : String(typeof value === "bigint" ? `${value}n` : JSON.stringify(value) ?? String(value));
console.log(typeof value, label.slice(0, 20));
}undefined undefined
object null
boolean true
number 42
string "text"
bigint 9007199254740993n
symbol Symbol(id)
object {"id":1}
object [1,2]
function () => {}
object "1970-01-01T00:00:00
object {}
object {}
function class Order {}Eight distinct typeof results appear, and the list has fourteen values. Three of the values report "object" and are not what typeof suggests: null, which is a primitive, and the array and the date, which are objects of a particular kind. The function reports its own result, "function", though it is an object too, and the class is a function. The table below maps what you hold to what you should ask next.
| You hold | typeof says | What it really is | Check it with |
|---|---|---|---|
undefined | "undefined" | Primitive | === undefined |
null | "object" | Primitive | === null |
true | "boolean" | Primitive | typeof |
42 or NaN | "number" | Primitive, a 64-bit float | Number.isFinite() |
"text" | "string" | Primitive, UTF-16 | typeof |
10n | "bigint" | Primitive | typeof |
Symbol() | "symbol" | Primitive | typeof |
[] | "object" | Object | Array.isArray() |
() => {} | "function" | Object, callable | typeof |
new Date() | "object" | Object | instanceof or a tag |
The rest of the guide goes through the rows.
undefined and null: two kinds of nothing
The engine produces undefined whenever a value is missing: an unset variable, an absent property, an omitted argument, a function with no return. null is a value a person assigns to mean "empty on purpose". The distinction decides what default values do, how JSON treats a field and what a database column means, and it is covered in depth in the post on null and undefined.
function describe({ name = "guest", retries = 3 } = {}) {
return `${name}:${retries}`;
}
console.log(describe(), describe({ name: undefined }), describe({ name: null, retries: null }));
console.log(null == undefined, null === undefined, null == 0, undefined == 0);
console.log(JSON.stringify({ a: undefined, b: null }), JSON.stringify([undefined, null]));
console.log(Number(null), Number(undefined), `${null} ${undefined}`);
const maybe = { value: null };
console.log(maybe.value ?? "fallback", maybe.value || "fallback", maybe.missing?.deeper);guest:3 guest:3 null:null
true false false false
{"b":null} [null,null]
0 NaN null undefined
fallback fallback undefinedDefaults replaced undefined and left null alone, which is why describe({ name: null }) printed null. Loose equality pairs the two with each other and with nothing else. JSON dropped the undefined property and wrote the null one, and arrays turned both into null. The numeric conversion differs: null becomes 0 and undefined becomes NaN. The practical rules are short. Let the language produce undefined for missing, use null only where a format needs an explicit empty value, and normalize at the boundary so the rest of the program sees one kind. The test for "either" is value == null, the one use of loose equality that style guides allow, and ?? and ?. are built on the same pairing, as covered in the post on optional chaining and the post on nullish coalescing.
typeof and its gaps
typeof returns one of eight strings. It never throws on an undeclared name, which makes it the probe for globals, and it is wrong about null and silent about arrays.
console.log(typeof undeclaredName, typeof null, typeof [], typeof NaN, typeof class {});
console.log(Array.isArray([]), Object.prototype.toString.call(null), Object.prototype.toString.call(new Date(0)));
function kind(value) {
if (value === null) return "null";
if (Array.isArray(value)) return "array";
if (value instanceof Date) return "date";
return typeof value;
}
console.log([null, [], new Date(0), {}, "x", 1n, undefined].map(kind));
function isPlainObject(value) {
if (typeof value !== "object" || value === null) return false;
const prototype = Object.getPrototypeOf(value);
return prototype === Object.prototype || prototype === null;
}
console.log(isPlainObject({}), isPlainObject([]), isPlainObject(new Date()), isPlainObject(Object.create(null)));undefined object object number function
true [object Null] [object Date]
[ 'null', 'array', 'date', 'object', 'string', 'bigint', 'undefined' ]
true false false trueThe first line collects the standard surprises: an undeclared name is "undefined" without an error, null is "object", an array is "object", NaN is "number" and a class is "function". A small kind function that checks null first and arrays second gives the answer people expect, and isPlainObject is the check that validation code actually needs. The post on typeof covers the temporal dead zone exception, the one place where the operator can throw.
Numbers: one type, with limits
A number is a 64-bit IEEE 754 double. It holds integers and fractions, Infinity, -Infinity, NaN and a negative zero, and three limits follow from the format: integers are exact only up to 2^53 - 1, decimal fractions are stored as binary approximations, and bitwise operators work on 32 bits.
console.log(Number.MAX_SAFE_INTEGER, 2 ** 53 + 1 === 2 ** 53, 9007199254740993);
console.log(0.1 + 0.2, 0.1 + 0.2 === 0.3, Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON);
console.log(1 / 0, -1 / 0, 0 / 0, 0 === -0, Object.is(0, -0));
console.log(2 ** 32 | 0, 2 ** 31 | 0, (2 ** 32 + 5) >>> 0);
console.log(Number.isInteger(5.0), Number.isSafeInteger(2 ** 53), (1.005).toFixed(2), Math.round(1.005 * 100) / 100);9007199254740991 true 9007199254740992
0.30000000000000004 false true
Infinity -Infinity NaN true false
0 -2147483648 5
true false 1.00 1An integer past the limit is silently rounded, and a decimal sum misses its target by a unit in the seventeenth place. Division by zero gives Infinity and never an error, and -0 is a real value that === cannot see. Bitwise operations wrap at 32 bits. And toFixed rounds the stored binary value, so 1.005 goes down. The format is explained in the post on how numbers work, the rounding cause in the post on 0.1 plus 0.2 and the bit operations in the post on bitwise operators.
Money belongs in integers, and tolerances belong in comparisons.
const cents = [1999, 549, 1];
const subtotal = cents.reduce((sum, value) => sum + value, 0);
const tax = Math.round(subtotal * 0.0825);
console.log(subtotal, tax, ((subtotal + tax) / 100).toFixed(2));
const nearlyEqual = (a, b) => Math.abs(a - b) <= Number.EPSILON * Math.max(1, Math.abs(a), Math.abs(b));
console.log(nearlyEqual(0.1 + 0.2, 0.3), nearlyEqual(1, 1.001));
console.log(new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format((subtotal + tax) / 100));2549 210 27.59
true false
$27.59All arithmetic happened on integers, with one rounding step for the tax, and the division by 100 happened at the edge for display. The Intl post covers formatting, and rounding rules belong in one function the whole codebase shares.
NaN deserves its own habit, because it spreads. Any arithmetic with a NaN returns NaN, and NaN is the only value not equal to itself.
console.log(NaN === NaN, Number.isNaN(NaN), isNaN("abc"), Number.isNaN("abc"), Object.is(NaN, NaN));
console.log([NaN].includes(NaN), [NaN].indexOf(NaN), new Set([NaN, NaN]).size, JSON.stringify({ n: NaN }));
function parseQuantity(text) {
const trimmed = String(text).trim();
if (trimmed === "") return null;
const value = Number(trimmed);
return Number.isFinite(value) ? value : null;
}
console.log(["12", " 3.5 ", "", "12px", "Infinity", "0x1f", "1e3"].map(parseQuantity));false true true false true
true -1 1 {"n":null}
[
12, 3.5, null,
null, null, 31,
1000
]Number.isNaN() is the test, and the global isNaN converts first, which is why it says true for "abc". The parser at the end rejects the blank string, which Number would turn into 0, and rejects Infinity, while accepting hex and exponent forms that Number understands. The post on NaN goes through the sources and the detection.
BigInt: integers without a ceiling
bigint holds integers of any size. It does not mix with number, has no Math support and cannot be written to JSON directly, and those limits are deliberate.
console.log(2n ** 64n, 9007199254740993n, BigInt(Number.MAX_SAFE_INTEGER) + 2n);
console.log(7n / 2n, -7n / 2n, 7n % 2n, typeof 1n, 1n == 1, 1n === 1, 0n ? "t" : "f");
try {
console.log(1n + 1);
} catch (error) {
console.log(error.name + ": " + error.message);
}
const text = JSON.stringify({ id: 9007199254740993n }, (key, value) => (typeof value === "bigint" ? value.toString() : value));
console.log(text, BigInt(JSON.parse(text).id));18446744073709551616n 9007199254740993n 9007199254740993n
3n -3n 1n bigint true false f
TypeError: Cannot mix BigInt and other types, use explicit conversions
{"id":"9007199254740993"} 9007199254740993nDivision truncates toward zero, comparisons across the two types work and strict equality does not. Mixing arithmetic throws, and JSON needs a replacer. Use bigint for ids above 2^53 and for exact integer arithmetic, and ship ids across JSON boundaries as strings. The BigInt post has the fixed-width and parsing details.
Strings: UTF-16 text
A string is a sequence of 16-bit code units. length, indexing and slice() count code units, and characters beyond U+FFFF take two. What a person sees as one character can be several code points, and several code points can be one grapheme.
const samples = ["a", "é", "é", "😀", "👨👩👧"];
const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
for (const text of samples) {
console.log(JSON.stringify(text).padEnd(10), text.length, [...text].length, [...segmenter.segment(text)].length);
}
console.log("café" === "café", "café".normalize() === "café".normalize());
console.log("a😀b".split("").reverse().join("") === "b😀a", [..."a😀b"].reverse().join(""));
console.log("😀".slice(0, 1).length, "😀".isWellFormed(), "😀".slice(0, 1).isWellFormed());"a" 1 1 1
"é" 1 1 1
"é" 2 2 1
"😀" 2 1 1
"👨👩👧" 8 5 1
false true
false b😀a
1 true falseThe columns are code units, code points and graphemes. Two spellings of "café" are different strings until normalized. Reversing by code unit breaks an emoji and reversing by code point does not. A lone surrogate is not well-formed Unicode. The posts on UTF-16 strings and Unicode go through counting, truncation, normalization and comparison.
Template literals convert every interpolation to a string, and tagged templates receive the pieces apart, which is the foundation of safe query and markup builders, as shown in the post on template literals.
Symbols: unique keys and language hooks
A symbol is a primitive whose every value is unique. It is a property key that cannot collide, and the well-known symbols are the hooks that let objects join iteration, conversion and type checks.
const a = Symbol("id");
const b = Symbol("id");
console.log(a === b, Symbol.for("k") === Symbol.for("k"), a.description, String(a));
const record = { name: "Ada", [a]: "hidden" };
console.log(Object.keys(record), JSON.stringify(record), Reflect.ownKeys(record));
try {
console.log("" + a);
} catch (error) {
console.log(error.name + ": " + error.message);
}false true id Symbol(id)
[ 'name' ] {"name":"Ada"} [ 'name', Symbol(id) ]
TypeError: Cannot convert a Symbol value to a stringSymbol keys are skipped by Object.keys() and by JSON, and implicit conversion to a string throws. The symbols post covers the registry and the hooks.
Truthiness: eight falsy values
Conditions, !, &&, || and ?: convert their operand to a boolean, and there are exactly eight values that become false.
const falsy = [false, 0, -0, 0n, "", null, undefined, NaN];
const surprising = [[], {}, "0", "false", " ", new Boolean(false), -1, Infinity];
console.log(falsy.map(Boolean).every((v) => v === false));
console.log(surprising.map(Boolean).every((v) => v === true));
console.log(0 || 10, 0 ?? 10, "" || "x", "" ?? "x", false || true, false ?? true);
console.log([] == false, Boolean([]), "0" == false, Boolean("0"));
function paginate(options) {
return { pageSize: options.pageSize ?? 20, showTotal: options.showTotal ?? true };
}
console.log(paginate({ pageSize: 0, showTotal: false }), paginate({}));true
true
10 0 x true false
true true true true
{ pageSize: 0, showTotal: false } { pageSize: 20, showTotal: true }Everything not on the falsy list is truthy, including empty arrays and the string "0". || replaces any falsy value and ?? only the missing ones, which is the whole difference between a default that respects zero and one that does not. And truthiness is not equality: [] == false is true while [] is truthy, because == converts by a different path. The list post has the table.
Equality: four comparisons
JavaScript has four ways to ask whether two values are the same. Strict equality === compares type and value. Loose equality == converts first. Object.is is strict equality with NaN equal to itself and the two zeros different. And SameValueZero, used by includes(), Set and Map, is Object.is with the zeros equal.
const pairs = [[1, "1"], [0, ""], [0, "0"], ["", "0"], [null, undefined], [null, 0], [NaN, NaN], [0, -0], [[], false], ["b" + "a", "ba"]];
for (const [left, right] of pairs) {
console.log(
JSON.stringify(left) ?? String(left),
JSON.stringify(right) ?? String(right),
"| ==", left == right, "| ===", left === right, "| is", Object.is(left, right),
);
}
const x = { id: 1 };
console.log(x === { id: 1 }, x === x, [x].includes({ id: 1 }), [x].includes(x));1 "1" | == true | === false | is false
0 "" | == true | === false | is false
0 "0" | == true | === false | is false
"" "0" | == false | === false | is false
null undefined | == true | === false | is false
null 0 | == false | === false | is false
null null | == false | === false | is true
0 0 | == true | === true | is false
[] false | == true | === false | is false
"ba" "ba" | == true | === true | is true
false true false trueRead the third and fourth rows together: 0 == "" and 0 == "0" are true while "" == "0" is false, so loose equality is not transitive. Objects compare by identity in every one of the four. The rules are laid out in the post on loose and strict equality, the two exceptions in the post on Object.is and the object case in the post on equality for objects and arrays. The default is ===, with value == null as the one exception.
The three conversions
Every implicit conversion ends in one of three operations. ToString produces text, ToNumber produces a number and ToBoolean produces a boolean. The table below is the complete behavior for primitives, and objects go through ToPrimitive first.
| Input | ToString | ToNumber | ToBoolean |
|---|---|---|---|
undefined | "undefined" | NaN | false |
null | "null" | 0 | false |
true, false | "true", "false" | 1, 0 | itself |
| number | decimal text | itself | false for 0, -0, NaN |
| string | itself | parsed or NaN | false for "" |
| bigint | decimal text | throws | false for 0n |
| symbol | throws (implicit) | throws | true |
| object | via ToPrimitive | via ToPrimitive | true |
console.log(String(null), String(true), String(123n), String([1, [2, 3]]), String({}), String(() => 1));
console.log(Number(""), Number(" "), Number("12px"), Number("0x1f"), Number("1e3"), Number(true), Number([]), Number([5]), Number([1, 2]));
console.log(Boolean(""), Boolean(" "), Boolean(0n), Boolean(Symbol()), Boolean([]));
console.log(parseInt("12px", 10), parseFloat("3.5kg"), parseInt("0x1f", 16), parseInt("08", 10), +"", +" 42 ", -"3");null true 123 1,2,3 [object Object] () => 1
0 0 NaN 31 1000 1 0 5 NaN
false true false true true
12 3.5 31 8 0 42 -3String to number conversion is strict and trims whitespace: trailing text gives NaN, and an empty or blank string gives 0. parseInt and parseFloat read a numeric prefix and ignore the rest, which is the right tool for "3.5kg" and the wrong one for validation. The coercion post walks through each operator.
Which operator uses which conversion
The operator decides the target. This is the part to remember.
console.log("5" - 3, "5" * "2", "10" / 4, "7" % 4, +"42", true + 1, null + 1, undefined + 1);
console.log("5" + 3, 1 + 2 + "3", "1" + 2 + 3, [] + [], [1, 2] + [3], {} + "", null + "x");
console.log(3 > "12", "3" > "12", "a" < "b", "B" < "a", null >= 0, undefined >= 0);
console.log([10, 9, 1].sort(), [10, 9, 1].sort((a, b) => a - b));
console.log(`${[1, 2]} ${{}} ${null} ${undefined} ${1n}`);2 10 2.5 3 42 2 1 NaN
53 33 123 1,23 [object Object] nullx
false true true true true false
[ 1, 10, 9 ] [ 1, 9, 10 ]
1,2 [object Object] null undefined 1-, *, /, % and unary + always produce numbers. + concatenates when either side is a string after conversion, and evaluation goes left to right, so the type changes mid-expression. Relational operators compare numbers unless both sides are strings, in which case they compare code units, and the default sort does the string comparison, which puts 10 before 9. Template literals use ToString on everything.
Objects to primitives
When an object meets an operator that needs a primitive, the engine calls Symbol.toPrimitive with a hint, or valueOf() then toString() in an order the hint sets. Dates default to the string hint, and plain objects stringify to [object Object].
const order = {
valueOf() {
return 42;
},
toString() {
return "order-42";
},
};
console.log(`${order}`, order + 1, order * 2, order + "", String(order));
class Money {
constructor(cents) {
this.cents = cents;
}
[Symbol.toPrimitive](hint) {
return hint === "string" ? `$${(this.cents / 100).toFixed(2)}` : this.cents;
}
}
const price = new Money(1250);
console.log(`${price}`, price + 50, price > 1000, price == 1250);
const date = new Date(86400000);
console.log(typeof (date + 1), typeof (date - 1), date - new Date(0));order-42 43 84 42 order-42
$12.50 1300 true true
string number 86400000The hint is "string" for templates and String(), "number" for arithmetic and comparison and "default" for + and ==. The post on converting objects to primitives covers the failure when no primitive comes back.
Conversion at the boundary
Data enters a program as text: form fields, query strings, environment variables, CSV cells, JSON. The habit that prevents most type bugs is to convert once, at the edge, with a function that validates, and to keep the rest of the program typed.
const parseBoolean = (text) => (text === "true" ? true : text === "false" ? false : null);
const parseDate = (text) => {
const time = Date.parse(text);
return Number.isNaN(time) ? null : new Date(time);
};
function parseOrder(raw) {
const quantity = Number(raw.quantity);
return {
id: String(raw.id),
quantity: Number.isInteger(quantity) && quantity > 0 ? quantity : null,
gift: parseBoolean(raw.gift),
placed: parseDate(raw.placed),
};
}
console.log(parseOrder({ id: 7, quantity: "3", gift: "false", placed: "2026-05-06T10:00:00Z" }));
console.log(parseOrder({ id: "x", quantity: "3.5", gift: "yes", placed: "later" }));
console.log(parseOrder({ id: 1, quantity: "", gift: "true", placed: undefined }));{ id: '7', quantity: 3, gift: false, placed: 2026-05-06T10:00:00.000Z }
{ id: 'x', quantity: null, gift: null, placed: null }
{ id: '1', quantity: null, gift: true, placed: null }Each field was converted by a function that says what a bad value looks like, null here, so downstream code checks for one kind of failure. A boolean parsed from "false" with Boolean("false") would be true, which is one of the most common bugs in form handling. A schema library does the same job with less code and better messages, and it is the right choice when a payload has many fields.
JSON and types
JSON has six types: object, array, string, number, boolean and null. Everything else is converted or lost on the way through, and the round trip does not restore it.
const source = {
date: new Date(Date.UTC(2026, 4, 6)),
set: new Set([1]),
map: new Map([["k", 1]]),
undef: undefined,
nan: NaN,
big: Infinity,
fn() {},
sym: Symbol("s"),
nested: { list: [1, undefined, () => {}] },
};
const roundTrip = JSON.parse(JSON.stringify(source));
console.log(roundTrip);
console.log(typeof roundTrip.date, roundTrip.date);
const revived = JSON.parse('{"when":"2026-05-06T00:00:00.000Z","n":1}', (key, value) =>
key === "when" ? new Date(value) : value,
);
console.log(revived.when instanceof Date);{
date: '2026-05-06T00:00:00.000Z',
set: {},
map: {},
nan: null,
big: null,
nested: { list: [ 1, null, null ] }
}
string 2026-05-06T00:00:00.000Z
trueDates became strings, sets and maps became empty objects, and undefined, functions and symbols vanished or turned into null. A reviver restores a type by field name. The JSON post covers the replacer, toJSON and the large-number problem, and the post on structuredClone() is the type-preserving copy for in-memory data.
Collections and what they hold
The type of a container decides what keys and values it can hold. Objects have string and symbol keys and inherited names, arrays are objects with integer keys, Map accepts any key, and Set stores unique values.
const object = {};
object[1] = "number";
object["1"] = "string";
object[{}] = "object";
const map = new Map([[1, "number"], ["1", "string"], [NaN, "nan"]]);
console.log(Object.keys(object), map.size, map.get(NaN));
console.log("toString" in {}, Object.hasOwn({}, "toString"), "constructor" in Object.create(null));
console.log(new Set([1, "1", 1n, true, 1]).size, new Set([NaN, NaN, 0, -0]).size);
console.log(Object.groupBy([1, 2, 3, 4], (n) => (n % 2 ? "odd" : "even")), Map.groupBy([1, 2], (n) => n > 1).get(false));[ '1', '[object Object]' ] 3 nan
true false false
4 2
[Object: null prototype] { odd: [ 1, 3 ], even: [ 2, 4 ] } [ 1 ]The object collapsed the number and the string key and turned the object key into text. The map kept three distinct entries, the number, the string and NaN. A Set of 1, "1", 1n and true has four members even with a repeated 1, and a set holding two NaN and both zeros has two. Choose the container by the keys you have, as covered in the post on Sets and Maps, and use Object.hasOwn() for own properties, as in the post on objects.
Checking types at runtime
typeof and instanceof answer narrow questions, and real validation needs both together with the shape.
const isString = (value) => typeof value === "string";
const isNonEmptyString = (value) => isString(value) && value.trim() !== "";
const isFiniteNumber = (value) => typeof value === "number" && Number.isFinite(value);
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
function validateUser(input) {
const problems = [];
if (!isRecord(input)) return ["input must be an object"];
if (!isNonEmptyString(input.name)) problems.push("name must be a non-empty string");
if (!isFiniteNumber(input.age) || !Number.isInteger(input.age)) problems.push("age must be an integer");
if (input.tags !== undefined && !(Array.isArray(input.tags) && input.tags.every(isString))) problems.push("tags must be strings");
return problems;
}
console.log(validateUser({ name: "Ada", age: 36, tags: ["a"] }));
console.log(validateUser({ name: " ", age: "36", tags: [1] }));
console.log(validateUser(null), validateUser([]));[]
[
'name must be a non-empty string',
'age must be an integer',
'tags must be strings'
]
[ 'input must be an object' ] [ 'input must be an object' ]Each predicate asks one question, and the validator returns every problem and not only the first. Without TypeScript, this is the only guard between external data and your logic. With it, the compiler checks your own code, and these checks guard the boundary where the types end.
TypeScript and runtime types
TypeScript adds a type system on top of the language and erases it at compile time. It catches mixing a string with a number, a missing property and a possibly undefined value, and it cannot check what arrives at runtime.
type Row = { id: number; label?: string };
function parse(input: unknown): Row {
if (typeof input !== "object" || input === null) throw new TypeError("expected an object");
const { id, label } = input as Record<string, unknown>;
if (typeof id !== "number") throw new TypeError("id must be a number");
return { id, label: typeof label === "string" ? label : undefined };
}
const rows: Row[] = [{ id: 1, label: "a" }, { id: 2 }];
const labeled = rows.filter((row): row is Row & { label: string } => row.label !== undefined);The function takes unknown and narrows it with typeof, which is the correct signature for anything that crosses a boundary. The filter uses a type predicate to tell the compiler what a true result proves. The coercion rules in this guide are the same at runtime, because the compiled output is plain JavaScript. Enable strict, noUncheckedIndexedAccess and exactOptionalPropertyTypes, and treat any as a hole in the checks.
Tracing a wrong total, step by step
The best way to learn the rules is to use them on a bug. A report shows an order total of "0.1" + "0.2" style nonsense, and the cause could be any of five things. The method is to print the type and the value at each step, and to stop at the first line where the type is not what you expected.
const rows = [
{ sku: "A", price: "19.99", qty: "2" },
{ sku: "B", price: 5, qty: "1" },
{ sku: "C", price: "7.50", qty: "" },
];
function inspect(label, value) {
console.log(label.padEnd(16), typeof value, JSON.stringify(value) ?? String(value));
}
const naive = rows.reduce((sum, row) => sum + row.price * row.qty, 0);
inspect("naive total", naive);
const firstLine = rows[0].price * rows[0].qty;
inspect("line A", firstLine);
const joined = rows.reduce((sum, row) => sum + row.price, "");
inspect("price + price", joined);
inspect("qty of C", Number(rows[2].qty));
inspect("price of C", rows[2].price * rows[2].qty);naive total number 44.98
line A number 39.98
price + price string "19.9957.50"
qty of C number 0
price of C number 0The naive total is a number, so it looks plausible, and it is wrong in two ways that cancel the eye. The first line multiplied two strings, which worked because * converts both to numbers, and produced 39.98 with the usual binary rounding. The last row has an empty quantity, which became 0 and contributed nothing, so a missing quantity was silently counted as zero. The third check shows the other classic: starting a reduce with "" made + concatenate. Each of those is the same class of bug, a type conversion that nobody asked for.
The fix is to convert once, at the start, into a typed structure, and to make the conversion refuse bad input.
const rows = [
{ sku: "A", price: "19.99", qty: "2" },
{ sku: "B", price: 5, qty: "1" },
{ sku: "C", price: "7.50", qty: "" },
];
function toCents(text) {
const value = Number(String(text).trim());
if (!Number.isFinite(value) || String(text).trim() === "") return null;
return Math.round(value * 100);
}
function toQuantity(text) {
const value = Number(String(text).trim());
return Number.isInteger(value) && value > 0 ? value : null;
}
function normalize(row) {
return { sku: String(row.sku), cents: toCents(row.price), qty: toQuantity(row.qty) };
}
const clean = rows.map(normalize);
const bad = clean.filter((row) => row.cents === null || row.qty === null);
const total = clean
.filter((row) => !bad.includes(row))
.reduce((sum, row) => sum + row.cents * row.qty, 0);
console.log(clean);
console.log(bad.map((row) => row.sku), total, (total / 100).toFixed(2));[
{ sku: 'A', cents: 1999, qty: 2 },
{ sku: 'B', cents: 500, qty: 1 },
{ sku: 'C', cents: 750, qty: null }
]
[ 'C' ] 4498 44.98The normalized rows carry integers and null for failures, the bad rows are reported by name and the total is computed only from good ones, in cents. A decision remains that the code cannot make for you: what to do with row C. Dropping it, failing the whole report or substituting a default are all defensible, and the choice belongs in a function with a name and a test, not in an accident of conversion.
Types in forms, URLs and environment variables
Three places deliver almost every external value as a string: HTML forms, URL query strings and process environment variables. In each, the type that matters, number, boolean or list, is a convention that your code must apply, and the conventions disagree.
const params = new URLSearchParams("page=2&limit=0&debug&tags=a&tags=b&empty=&flag=false");
console.log(params.get("page"), typeof params.get("page"), params.get("missing"));
console.log(params.has("debug"), params.get("debug"), params.getAll("tags"), params.get("empty") === "");
const page = Number(params.get("page") ?? 1);
const limit = Number(params.get("limit") ?? 20);
const emptyNullish = Number(params.get("empty") ?? 20);
const emptyOr = Number(params.get("empty") || 20);
console.log(page, limit, emptyNullish, emptyOr);
console.log(Boolean(params.get("flag")), params.get("flag") === "true");
const env = { PORT: "8080", WORKERS: "", DEBUG: "0", LIST: "a,b,,c" };
const toBool = (text, fallback = false) => (text === undefined ? fallback : ["1", "true", "yes", "on"].includes(text.toLowerCase()));
console.log(Number(env.PORT), Number(env.WORKERS), Number(env.WORKERS || 4), toBool(env.DEBUG), toBool(undefined, true));
console.log(env.LIST.split(","), env.LIST.split(",").filter(Boolean));2 string null
true [ 'a', 'b' ] true
2 0 0 20
true false
8080 0 4 false true
[ 'a', 'b', '', 'c' ] [ 'a', 'b', 'c' ]get() returns null for an absent parameter and a string for every present one, including a bare debug, which is the empty string, and flag=false, which is the truthy string "false". The pagination values show why the operator choice matters. limit=0 is the string "0", which is truthy, so both forms keep it, and the number is zero. The empty parameter is where they split: ?? keeps the empty string, which Number turns into 0, and || replaces it with the default. A query parameter that is present and empty usually means "unset", so || is the better operator there, and the same holds for environment variables, where an empty WORKERS almost always means "not configured". A comment should say which meaning you chose. Boolean flags need an explicit parser, since Boolean("0") and Boolean("false") are both true, and a list needs splitting and cleaning.
The rule is one conversion function per kind of value, in one module, with tests. Every place that reads a parameter or a variable calls it, so the convention is written once. A schema library gives the same guarantee for structured input and reports every problem at once, and it is worth adopting when a handler has more than a few fields.
Rounding, percentages and tax in business code
Numbers in business code carry rules that the language does not know: how many decimals, which way to round a half, when to round. The language gives you a double and Math.round, so the rules must live in your code, in one place, with names.
const roundHalfUp = (value, digits = 0) => {
const factor = 10 ** digits;
return Math.round((value + Number.EPSILON) * factor) / factor;
};
const roundHalfEven = (value) => {
const floor = Math.floor(value);
const diff = value - floor;
if (diff > 0.5) return floor + 1;
if (diff < 0.5) return floor;
return floor % 2 === 0 ? floor : floor + 1;
};
console.log([0.5, 1.5, 2.5, 3.5, -0.5, -1.5].map((n) => Math.round(n)));
console.log([0.5, 1.5, 2.5, 3.5].map(roundHalfEven));
console.log(roundHalfUp(1.005, 2), (1.005).toFixed(2), Math.round(1.005 * 100) / 100);
const percent = (part, whole) => (whole === 0 ? 0 : (part / whole) * 100);
console.log(percent(1, 3), roundHalfUp(percent(1, 3), 1), percent(5, 0));
const allocate = (cents, shares) => {
const base = Math.floor(cents / shares);
const remainder = cents - base * shares;
return Array.from({ length: shares }, (_, i) => base + (i < remainder ? 1 : 0));
};
console.log(allocate(100, 3), allocate(100, 3).reduce((a, b) => a + b, 0));[ 1, 2, 3, 4, -0, -1 ]
[ 0, 2, 2, 4 ]
1.01 1.00 1
33.33333333333333 33.3 0
[ 34, 33, 33 ] 100Math.round rounds halves toward positive infinity, so -0.5 rounds to -0 and 2.5 rounds to 3, which differs from the banker's rounding some financial rules require. The half-even function above shows the alternative, and the epsilon nudge in roundHalfUp fixes the 1.005 case at the price of being a heuristic: it works for typical values and is not a proof. The percentage helper guards the zero denominator, which would otherwise return Infinity or NaN and spread. The allocation function splits an amount into shares that add up exactly, giving the extra cents to the first shares, which is how a bill of 100 cents is divided among three people without losing one.
The rule is to choose the rounding mode your domain requires, implement it once and use it everywhere. When accountants and developers disagree about a cent, a single named function is the thing that gets fixed, and a hundred inline toFixed calls are the thing that does not.
Designing with absence and states
The type system gives you undefined and null for "nothing", and booleans for two states. Real data has more states than that, and encoding them as combinations of null and flags produces code that nobody can read. Naming the states makes the conversions disappear, because each state is a distinct value.
const Status = Object.freeze({
Idle: "idle",
Loading: "loading",
Loaded: "loaded",
Failed: "failed",
});
function render(state) {
switch (state.status) {
case Status.Idle:
return "nothing yet";
case Status.Loading:
return "loading...";
case Status.Loaded:
return state.data.length + " items";
case Status.Failed:
return "error: " + state.error.message;
default:
throw new TypeError("unknown status: " + String(state.status));
}
}
const states = [
{ status: Status.Idle },
{ status: Status.Loading },
{ status: Status.Loaded, data: [1, 2, 3] },
{ status: Status.Failed, error: new Error("timeout") },
];
console.log(states.map(render));
try {
render({ status: "weird" });
} catch (error) {
console.log(error.name + ": " + error.message);
}
const flagged = { loading: false, error: null, data: null };
console.log(!flagged.loading && !flagged.error && !flagged.data ? "idle?" : "something else");[ 'nothing yet', 'loading...', '3 items', 'error: timeout' ]
TypeError: unknown status: weird
idle?The tagged states are exhaustive by construction, each carries exactly the fields that make sense for it, and an unknown status fails loudly. The flag version at the end shows the alternative: three independent fields allow eight combinations, five of which mean nothing, and every reader has to work out which ones the code can reach. In TypeScript the same shape is a discriminated union and the compiler checks that every case is handled. In plain JavaScript, a frozen object of string constants and a switch with a throwing default give most of the benefit.
Strings are the right choice for state names because they serialize and compare by value. A symbol would be unique and would not survive a JSON round trip, which is the wrong trade for anything that crosses a boundary.
Testing type handling
Type bugs hide in the inputs a developer does not think of, and the cheapest defense is a table of awkward inputs run through each conversion function. The built-in test runner is enough.
import { test } from "node:test";
import assert from "node:assert/strict";
function toQuantity(text) {
const value = Number(String(text).trim());
return Number.isInteger(value) && value > 0 ? value : null;
}
const accepted = [["1", 1], [" 12 ", 12], ["3.0", 3], ["1e2", 100], [7, 7]];
const rejected = ["", " ", "0", "-1", "1.5", "abc", "12px", "NaN", "Infinity", null, undefined, {}, []];
for (const [input, expected] of accepted) {
test(`accepts ${JSON.stringify(input)}`, () => {
assert.equal(toQuantity(input), expected);
});
}
for (const input of rejected) {
test(`rejects ${JSON.stringify(input) ?? String(input)}`, () => {
assert.equal(toQuantity(input), null);
});
}Run it with node --test on Node.js 24. The rejected list is the valuable half: it contains the blank string, which Number turns into zero, the exponent form, which Number accepts and a hand-written regex might not, and [], which converts to the empty string and then to zero. When a bug is found in production, add its input to the table and the test suite remembers it.
Property-style tests extend the idea: generate many values and assert an invariant, such as "the result is either null or a positive integer". A library such as fast-check does the generating, and a loop over a handful of random cases is a cheap first step.
Arrays, array-likes and iterables as types
The word "array" covers more than Array. Code meets array-likes, objects with a length and indexed properties, and iterables, objects that can be looped, and the three are not interchangeable. Knowing which you hold decides which methods work and which conversion to apply.
function demo() {
return arguments;
}
const arrayLike = { length: 2, 0: "a", 1: "b" };
const args = demo(1, 2, 3);
const set = new Set([1, 2]);
console.log(Array.isArray(args), args.length, typeof args.map, Array.from(args));
console.log(Array.isArray(arrayLike), Array.from(arrayLike), Array.prototype.map.call(arrayLike, (s) => s.toUpperCase()));
console.log(Array.isArray(set), typeof set.map, [...set], Array.from(set, (n) => n * 2));
console.log(Array.from("héy"), Array.from({ length: 3 }, (_, i) => i * i), Array.of(7), Array(3).length);
try {
[...arrayLike];
} catch (error) {
console.log(error.name);
}false 3 undefined [ 1, 2, 3 ]
false [ 'a', 'b' ] [ 'A', 'B' ]
false undefined [ 1, 2 ] [ 2, 4 ]
[ 'h', 'é', 'y' ] [ 0, 1, 4 ] [ 7 ] 3
TypeErrorThe arguments object and the hand-made object have a length and indexes and no array methods. A set is iterable and has neither. Array.from accepts both kinds, and spread accepts only iterables, so spreading the array-like throws. The array methods can be borrowed for an array-like with call, as the map example shows, and Array.from with a mapping function replaces a loop. The newer Array.fromAsync does the same for async sources, as described in the post on ES2026. When a function accepts "a list", decide whether it takes an array, an iterable or an array-like, and convert at the top so the body sees one type.
Freezing and the limits of runtime immutability
Some type errors are about change: a value that should not be edited and is. JavaScript has no immutable objects by default, and Object.freeze is the nearest tool. It makes an object's own properties read-only, one level deep, and it throws in strict mode when something tries to write.
const config = Object.freeze({ retries: 3, nested: { depth: 1 }, list: [1, 2] });
try {
config.retries = 5;
} catch (error) {
console.log(error.name);
}
config.nested.depth = 2;
config.list.push(3);
console.log(config.nested.depth, config.list, Object.isFrozen(config), Object.isFrozen(config.nested));
function deepFreeze(value) {
if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
Object.freeze(value);
for (const key of Reflect.ownKeys(value)) deepFreeze(value[key]);
}
return value;
}
const strict = deepFreeze({ retries: 3, nested: { depth: 1 }, list: [1, 2] });
try {
strict.list.push(3);
} catch (error) {
console.log(error.name);
}
console.log(Object.isFrozen(strict.nested), strict.list.length);TypeError
2 [ 1, 2, 3 ] true false
TypeError
true 2The shallow freeze blocked the top-level write and left the nested object and array editable. The recursive helper froze every level, and a push onto the frozen array threw. Freezing has a cost for large structures and is best reserved for configuration and constants. TypeScript's readonly and as const express the same intent at compile time at no runtime cost, and a convention of treating inputs as read-only and returning new values covers the rest, as discussed in the post on shallow and deep copies.
Sorting and comparing mixed values
Sorting is where comparison and conversion meet, and the default behavior is the least useful one. sort() without an argument converts every item to a string and compares code units, so numbers, mixed arrays and text with accents all sort in ways nobody asked for.
console.log([10, 9, 1, 100].sort(), [10, 9, 1, 100].sort((a, b) => a - b));
console.log(["b", "a", "B", "A", "ä", "z"].sort());
console.log(["b", "a", "B", "A", "ä", "z"].sort((x, y) => x.localeCompare(y)));
console.log(["file10", "file2", "file1"].sort(new Intl.Collator(undefined, { numeric: true }).compare));
console.log([3, undefined, 1, null, 2].sort(), [3, undefined, 1, 2].sort((a, b) => a - b));
const people = [{ name: "Grace", age: 85 }, { name: "Ada", age: 36 }, { name: "Linus", age: 36 }];
const byAgeThenName = [...people].sort((a, b) => a.age - b.age || a.name.localeCompare(b.name));
console.log(byAgeThenName.map((p) => p.name));
console.log([true, false, true].sort(), [{ n: 2 }, { n: 1 }].sort().map((o) => o.n));[ 1, 10, 100, 9 ] [ 1, 9, 10, 100 ]
[ 'A', 'B', 'a', 'b', 'z', 'ä' ]
[ 'a', 'A', 'ä', 'b', 'B', 'z' ]
[ 'file1', 'file2', 'file10' ]
[ 1, 2, 3, null, undefined ] [ 1, 2, 3, undefined ]
[ 'Ada', 'Linus', 'Grace' ]
[ false, true, true ] [ 2, 1 ]The numeric sort needs a comparator, because 10 sorts before 9 as text. The plain string sort puts uppercase letters before lowercase and ä last, and localeCompare and Intl.Collator sort by language rules, with the numeric option placing file2 before file10. Undefined values are always moved to the end by sort, before the comparator is called, which is why the comparator with undefined in the data does not return NaN for them. The two-key sort chains comparators with ||, which works because a.age - b.age is 0 when the ages are equal and 0 is falsy. Sorting objects without a comparator compares their string form, which is [object Object] for all of them, so the order is unchanged. The non-mutating toSorted() in Node.js 20 and later is the version to use on data you do not own.
Puzzles and what they teach
Lists of "weird JavaScript" expressions circulate for fun, and each of them is a short exercise in the rules above. Working them out is a useful test of understanding, and getting one wrong points at the rule to reread.
const puzzles = [
["[] + []", () => [] + []],
["[] + {}", () => [] + {}],
["[1] == 1", () => [1] == 1],
["[] == ![]", () => [] == ![]],
["'b' + 'a' + +'a' + 'a'", () => "b" + "a" + +"a" + "a"],
["0.1 * 3", () => 0.1 * 3],
["9007199254740993", () => 9007199254740993],
["typeof NaN", () => typeof NaN],
["null >= 0", () => null >= 0],
["'2' > '12'", () => "2" > "12"],
["[10, 1, 3].sort()", () => [10, 1, 3].sort()],
["parseInt('08')", () => parseInt("08")],
["Math.max()", () => Math.max()],
["1 < 2 < 3, 3 > 2 > 1", () => [1 < 2 < 3, 3 > 2 > 1]],
];
const show = (value) => (typeof value === "number" || typeof value === "boolean" ? String(value) : JSON.stringify(value));
for (const [expression, run] of puzzles) {
console.log(expression.padEnd(26), show(run()));
}[] + [] ""
[] + {} "[object Object]"
[1] == 1 true
[] == ![] true
'b' + 'a' + +'a' + 'a' "baNaNa"
0.1 * 3 0.30000000000000004
9007199254740993 9007199254740992
typeof NaN "number"
null >= 0 true
'2' > '12' true
[10, 1, 3].sort() [1,10,3]
parseInt('08') 8
Math.max() -Infinity
1 < 2 < 3, 3 > 2 > 1 [true,false]Each line has a short explanation in terms of the rules. The two arrays concatenate as empty strings. An array and an object become "" and "[object Object]". The array equals one because its string form is "1" and then a number. The [] == ![] line is true because ![] is false, which becomes 0, and [] becomes "" and then 0. The banana line applies a unary plus to a string that is not a number, producing NaN. Next come the float and the large integer, the typeof of NaN, null converting to 0 for relational operators and string comparison by code unit. Math.max() with no arguments is -Infinity, the identity of the operation, and the chained comparisons compare a boolean with a number. None of these is random, and none of them is a good reason to dislike the language: they are the cost of implicit conversion, and you can avoid every one by converting explicitly.
A catalogue of type bugs and their fixes
The bugs repeat, and each has a short fix. This list is arranged by symptom.
| Symptom | Cause | Fix | ||
|---|---|---|---|---|
"5" + 3 gives "53" | + concatenates with a string | Convert with Number() at the boundary | ||
| A zero or empty string is replaced by a default | ` | ` treats falsy as missing | Use ?? | |
NaN in a total | An unparsed or missing value reached arithmetic | Validate with Number.isFinite() when parsing | ||
| An id loses its last digits | Integer above 2^53 as a number | Keep it a string or bigint | ||
new Boolean("false") is truthy | An object is always truthy | Compare with === "true" | ||
| A filter drops zero values | filter(Boolean) removes 0 | Filter with != null | ||
[10, 9, 1].sort() gives [1, 10, 9] | Default sort compares strings | Pass (a, b) => a - b | ||
typeof null === "object" branch runs on null | typeof quirk | Check === null first | ||
arr.includes({ id: 1 }) is false | Objects compare by identity | Compare by a key with some() | ||
| A date shows the day before | A date-only string parses as UTC | Format with timeZone: "UTC" or use PlainDate | ||
A user-entered "1,5" becomes NaN | Locale decimal separator | Parse with a locale-aware routine | ||
| Money drifts by cents | Floating point decimals | Store integer cents |
console.log([0, 1, "", "a", null, undefined].filter(Boolean), [0, 1, "", "a", null, undefined].filter((v) => v != null));
console.log(new Boolean("false") ? "truthy" : "falsy", "false" === "true");
console.log([1, 2, 10].sort(), [1, 2, 10].sort((a, b) => a - b));
console.log(Number("1,5"), Number("1.5"), parseFloat("1,5"));
console.log([{ id: 1 }].some((item) => item.id === 1), [{ id: 1 }].includes({ id: 1 }));[ 1, 'a' ] [ 0, 1, '', 'a' ]
truthy false
[ 1, 10, 2 ] [ 1, 2, 10 ]
NaN 1.5 1
true falseEach line is one row of the table, with the wrong form and the right one together. Most of these are caught by lint rules and by TypeScript, and the ones that survive are about data that crossed a boundary, which is why the boundary deserves the most attention.
Types and performance
Engines run code faster when it sees consistent types. A function that always receives numbers is compiled to machine code that assumes numbers, and a function that sees numbers, strings and objects in turn is compiled to something slower and more general. Objects benefit from the same consistency: records built with the same fields in the same order share a layout, and objects whose shape changes, through delete or by adding properties in varying order, do not.
This matters in two places. In hot loops over large collections, keeping element types uniform, all numbers or all records of one shape, helps the engine, and typed arrays are the extreme case, with one element type guaranteed. And in libraries that are called from many places, accepting one kind of argument and normalizing at the top keeps the inner code monomorphic. For ordinary application code, none of this is visible, and we would not restructure code for it without a profile showing the cost. The useful consequence is that the style that is clearest to read, consistent types and consistent shapes, is also the style that engines handle best.
Migrating loose code to strict habits
An old codebase has loose equality in a thousand places, falsy defaults in a hundred and a handful of conversions nobody remembers writing. Tightening it all at once is risky, because some code depends on the loose behavior. A sequence that works is to tighten the checks first and the code second.
Start by enabling lint rules as warnings: eqeqeq with the null: "ignore" option, no-implicit-coercion, @typescript-eslint/strict-boolean-expressions if you use TypeScript and prefer-nullish-coalescing. Read the list and sort it into three piles. Obvious fixes, such as == 0 against a number that is always a number, change mechanically. Suspicious ones, such as if (value) on something that might be 0, need a test and a decision. And intentional ones, such as value == null, get a comment or an exemption. Add a test for every suspicious line before changing it, with the awkward inputs from the table above, and change the code until the tests pass.
Then move the boundary. Find where external data enters, requests, files and storage, and put the conversion functions there. After that, code inside the boundary can assume types, and the interior checks can be removed as they become redundant. The order matters: converting at the edge first makes the interior safe to tighten, and tightening the interior first only moves the bugs.
Reading the specification for a type question
When a result surprises you and nothing above explains it, the specification does. It is written as algorithms, and the type questions reduce to a few named operations. Search the specification for ToPrimitive, ToNumber, ToString, ToBoolean, IsLooselyEqual and SameValueZero, and read the steps in order. The text is precise and short for these, each is a page, and it names every case, including the ones the tables in this guide summarize.
A habit that makes the specification readable is to translate each step into a line of code and run it. The algorithm for loose equality, for example, is a list of cases, and writing it as a function and testing it against == for a few hundred pairs is a good afternoon's exercise and the most reliable way to learn the rules by heart. When the specification and an engine disagree, the engine is nearly always right about what ships, and the shared test suite is the place to check, as described in the post on JavaScript engines.
Habits worth keeping
Five habits carry most of what this guide covers, and they are small enough to keep in mind while writing. Convert where data enters, and validate there. Compare with ===, and write the one exception, == null, on purpose. Write defaults with ?? unless an empty string should also fall back, and say so when it should. Keep money in integers and ids in strings, and name the rounding rule. And write one test per conversion function with the awkward inputs in a table, because the inputs you did not think of are the ones that reach production. These habits cost minutes per function and remove a category of bug that otherwise returns every few months, in a different file, with a different symptom.
A review checklist
When you read code that handles values of mixed or external origin, five questions find most problems. Where did this value come from, and has it been converted and validated? What does each operator in this expression convert its operands to? Is a falsy value a legitimate input that a default or a condition would swallow? Is the comparison strict, and if not, is it the == null idiom? And could the number exceed 2^53, hold a fraction that matters or be NaN? Writing the answers next to a tricky line, in a comment, is a good way to find out whether they are known.
Where these rules stop
The rules in this guide describe the language, and the boundaries of a real program have rules of their own. A database driver maps types its own way, with decimals as strings, big integers as bigint or text and dates as Date objects. HTTP libraries parse JSON and sometimes revive types. Form libraries deliver strings for every field. In each case, read what the library does and convert explicitly. And in a typed codebase, resist the urge to cast with as at the boundary: a cast is a promise the compiler cannot check, and a runtime validator is the way to keep it.
The conversions and type definitions are specified in ECMAScript language types and type conversion, and MDN's data types and data structures page and its equality comparisons page are the readable companions.


