Sub topic 19
Writing Predictable Code: Coercion Best Practices
This chapter assumes you have worked through the earlier chapters. You should already know how ToPrimitive, ToNumber, ToString, and ToBoolean behave, and how ==, +, and the relational operators apply them. This chapter turns those rules into habits that keep coercion from surprising you or the people who read your code.
The main idea is to convert at the boundaries and compare strictly inside. Data from forms, URLs, JSON, environment variables, and storage arrives in a loose or unknown shape. Convert and validate it once, as soon as it enters your program. After that, the rest of your code works with values whose types are known, so implicit coercion has nothing to do.
Practice 1: Use === by Default
Strict equality never converts its operands, so its result depends only on the two values you can see. Loose equality runs the multi-step algorithm from the earlier chapter. Code that relies on it makes every reader run that algorithm in their head too.
Many teams allow one exception: value == null. This comparison is true only for null and undefined, because null loosely equals nothing else. It is a short, well-known way to test for "no value".
function describe(value) {
if (value == null) return "missing"; // null or undefined only
if (value === 0) return "zero";
return "present";
}
console.log(describe(undefined)); // "missing"
console.log(describe(null)); // "missing"
console.log(describe(0)); // "zero"
console.log(describe("")); // "present"If your team prefers no exceptions, write value === null || value === undefined. Both forms are fine. Pick one and use it everywhere.
Practice 2: Convert Explicitly and Validate the Result
Call Number(), String(), or Boolean() yourself rather than letting an operator do it quietly. Then check the result. Number() gives NaN for bad input, but it also accepts input you may not want. The empty string becomes 0, "0x10" becomes 16, and "1e3" becomes 1000.
When the format matters, check the text first and convert second:
function parseQuantity(input) {
if (typeof input !== "string") return null;
const trimmed = input.trim();
if (!/^\d+$/.test(trimmed)) return null; // digits only
const n = Number(trimmed);
return Number.isSafeInteger(n) ? n : null; // reject precision loss
}
console.log(parseQuantity(" 7 ")); // 7
console.log(parseQuantity("")); // null (Number("") would give 0)
console.log(parseQuantity("0x10")); // null (Number("0x10") would give 16)
console.log(parseQuantity("2.5")); // null
console.log(parseQuantity("12px")); // null
console.log(parseQuantity("99999999999999999")); // nullUse the Number. versions of the checking functions. The global isNaN and isFinite coerce their argument before testing it. Number.isNaN and Number.isFinite do not.
console.log(isFinite("12")); // true: "12" was coerced
console.log(Number.isFinite("12")); // false: not a number
console.log(Number.isNaN("abc")); // false: not the NaN valuePractice 3: Use ?? for Defaults
|| falls back on any falsy value, so it throws away valid values such as 0, "", and false. ?? falls back only on null and undefined.
function createConfig(options) {
return {
retries: options?.retries ?? 3,
label: options?.label ?? "untitled",
verbose: options?.verbose ?? false,
};
}
console.log(createConfig({ retries: 0, label: "" }));
// { retries: 0, label: '', verbose: false }
console.log(createConfig(null));
// { retries: 3, label: 'untitled', verbose: false }Default parameters such as function f(options = {}) apply only when the argument is undefined. Passing null skips the default, and options.retries then throws a TypeError. Optional chaining (options?.retries) handles both cases.
Practice 4: Keep + Unambiguous
+ concatenates when either operand is a string. Expressions that mix strings and numbers therefore depend on evaluation order:
const total = 5;
console.log("Total: " + total + 1); // "Total: 51"
console.log(`Total: ${total + 1}`); // "Total: 6"
const fromInput = "5";
console.log(fromInput + 1); // "51"
console.log(Number(fromInput) + 1); // 6Use template literals to build strings. Convert operands to numbers before you do arithmetic. If a value might be a BigInt, convert it on purpose with Number(big) or BigInt(n). Mixing the two throws a TypeError, and that error tells you a conversion is missing.
Practice 5: Be Explicit When Falsy Values Are Valid
if (value) is a fine way to ask "is there something here?" when 0, "", and false cannot be valid data. When they can be valid, test for exactly the condition you mean:
| Intent | Ambiguous | Precise |
|---|---|---|
| Value was provided | `if (value)` | `if (value != null)` |
| Array has items | `if (arr.length)` | `if (arr.length > 0)` |
| String is non-empty | `if (str)` | `if (typeof str === "string" && str !== "")` |
| Number is usable | `if (n)` | `if (Number.isFinite(n))` |
| Flag is on | `if (flag)` | `if (flag === true)` |
Practice 6: Compare Values of the Same Type
The relational operators compare two strings by UTF-16 code units and convert everything else to numbers. Sorting shows the same trap: by default, Array.prototype.sort converts elements to strings.
console.log([10, 9, 1].sort()); // [1, 10, 9]
console.log([10, 9, 1].sort((a, b) => a - b)); // [1, 9, 10]
const names = ["émile", "Zoe", "adam"];
console.log([...names].sort()); // [ 'Zoe', 'adam', 'émile' ]
console.log([...names].sort((a, b) => a.localeCompare(b))); // [ 'adam', 'émile', 'Zoe' ]Convert both sides to the same type before you compare them. Use localeCompare or Intl.Collator when the order will be shown to people.
Practice 7: Check Types with the Right Tool
Use Array.isArray for arrays and value === null for null. Use typeof for primitives and functions. Remember that typeof null is "object", so a plain-object check needs typeof v === "object" && v !== null.
Let Tools Enforce the Rules
Write these habits down as lint rules so reviewers don't have to catch every slip. ESLint's eqeqeq rule bans == while optionally allowing the null idiom. no-implicit-coercion flags shortcuts such as !!x, +x, and "" + x.
// eslint.config.js
export default [
{
rules: {
eqeqeq: ["error", "always", { null: "ignore" }],
"no-implicit-coercion": "error",
},
},
];TypeScript goes further. It rejects many mixed-type operations at compile time, for example adding an object to a number. Types still disappear at runtime, though, so you need to validate data at the boundary either way.
Summary of Trade-offs
| Choice | Benefit | Cost | Column | Column |
|---|---|---|---|---|
| `===` everywhere | No hidden conversion | Slightly longer null checks | ||
| `== null` exception | Short "no value" test | Readers must know the idiom | ||
| `Number()` plus validation | Exact control over accepted input | More code at boundaries | ||
| `??` over `\ | \ | ` | Keeps `0`, `""`, `false` | Does not catch `NaN` or `""` when you wanted to |
| Lint rules | Consistent enforcement | Initial cleanup of existing code |
Exercise
This function should return the page number from a query string value, defaulting to 1: function getPage(raw) { const page = parseInt(raw) || 1; return page; }. Name two inputs it handles wrongly and write a version that follows this chapter's practices, assuming pages start at 1.
Show answer
getPage("3abc") returns 3 because parseInt reads the leading prefix, and getPage("0") returns 1 because || replaces the valid-looking 0 (which should be rejected explicitly, not silently replaced). Calling parseInt without a radix is also a bad habit. A safer version: function getPage(raw) { if (typeof raw !== "string" || !/^\d+$/.test(raw.trim())) return 1; const n = Number(raw.trim()); return Number.isSafeInteger(n) && n >= 1 ? n : 1; }
Exercise
A teammate writes if (user.age) to check whether an age was entered, and if (a == b) to compare two IDs that might be a number or a numeric string. What would you change, and why?
Show answer
Replace if (user.age) with if (user.age != null) or Number.isFinite(user.age), because an age of 0 is falsy and would be treated as missing. For the IDs, convert both to one type at the boundary, for example String(a) === String(b), or better, normalize IDs when the data is loaded, so the comparison does not depend on the loose equality algorithm.