Sub topic 18
Writing Predictable Code: Coercion Best Practices
This chapter assumes you know the rules covered earlier: ToNumber, ToString, ToBoolean, ToPrimitive, the loose equality algorithm, and how || and ?? choose a value. It brings those rules together into a few habits that keep JavaScript from converting values in ways you did not plan.
Make Conversions Visible
Implicit coercion does work you can't see. Convert values yourself, at the point where they enter your program: form fields, query strings, JSON, environment variables. After that point, every value should already have the type the rest of the code expects.
function parseQuantity(input) {
const text = String(input).trim();
const n = Number(text);
if (text === "" || !Number.isInteger(n) || n < 0) {
throw new TypeError(`Invalid quantity: ${JSON.stringify(input)}`);
}
return n;
}
console.log(parseQuantity(" 3 ")); // 3
try {
parseQuantity(""); // Number("") would silently give 0
} catch (err) {
console.log(err.message); // Invalid quantity: ""
}The empty-string check is there because Number("") returns 0. That is a valid number, so an empty field would pass through unnoticed.
Pick Comparisons Deliberately
Use === by default. The one common exception is value == null, which matches exactly null and undefined and nothing else. Many teams allow it for that reason, and ESLint's eqeqeq rule has a "smart" option that permits it.
For relational operators, convert both sides to the same type first. Comparing "10" < "9" as strings gives true, which is almost never what you meant.
Recommended Habits
| Risky pattern | Predictable alternative | Why | Column | Column |
|---|---|---|---|---|
| `a == b` | `a === b` | No hidden conversion | ||
| `isNaN(x)` | `Number.isNaN(x)` | Does not coerce strings first | ||
| `opts.limit \ | \ | 10` | `opts.limit ?? 10` | Keeps valid `0` and `""` |
| `"Total: " + a + b` | `` `Total: ${a + b}` `` | Arithmetic runs before string building | ||
| `typeof x === "object"` | `Array.isArray(x)`, `x !== null` | Excludes arrays and `null` correctly | ||
| `if (arr.length)` on unknown input | `Array.isArray(arr) && arr.length > 0` | States the intent | ||
| `+str` | `Number(str)` | Easier to read and search for |
Use `+` Carefully
The + operator either adds or concatenates, depending on its operands. When the values come from outside your code, convert them with Number(...) before you add, and use template literals when you want a string. Never mix BigInt and Number values. Convert one side on purpose and handle any precision you lose.
Exercise
A config loader runs const port = env.PORT || 3000; and if (port == "0") disable();. Rewrite both lines so that an unset PORT defaults to 3000, PORT="0" disables the server, and no implicit coercion takes place.
Show answer
const port = env.PORT === undefined ? 3000 : Number(env.PORT); then if (port === 0) disable();. Converting with Number makes port a number in both cases. env.PORT ?? 3000 also works for the default, but it would leave port as a string when PORT is set, so the Number conversion would still be needed before the strict comparison with 0.
Exercise
Why is Number.isNaN(value) preferred over value !== value in shared code, even though both detect NaN?
Show answer
Both are correct, but Number.isNaN names its intent. value !== value relies on a quirk of NaN that readers may not recognize.