Sub topic 8
Validating Numbers with Number.isNaN, isFinite, isInteger, and isSafeInteger
This chapter assumes you already know three things from earlier chapters. You should know how NaN, Infinity, and -0 behave. You should know where the safe integer range ends, at Number.MAX_SAFE_INTEGER. You should also know how Number() converts strings. Here we use those ideas to answer a practical question: is this value a number I can trust?
JavaScript has four static predicates on the Number constructor for this job. Each one returns true or false, and none of them converts its argument first. That last point matters most. Older global functions with similar names do convert their argument, and mixing up the two families is one of the most common validation bugs.
The Four Predicates at a Glance
| Method | Returns `true` when the argument is... |
|---|---|
| `Number.isNaN(x)` | a number primitive whose value is `NaN` |
| `Number.isFinite(x)` | a number primitive that is not `NaN`, `Infinity`, or `-Infinity` |
| `Number.isInteger(x)` | a finite number primitive with no fractional part |
| `Number.isSafeInteger(x)` | an integer whose magnitude is at most `2 ** 53 - 1` |
All four return false for anything whose typeof is not "number". That includes strings, null, undefined, booleans, BigInts, and Number wrapper objects.
console.log(Number.isNaN(NaN)); // true
console.log(Number.isFinite(42)); // true
console.log(Number.isInteger(42)); // true
console.log(Number.isSafeInteger(42)); // true
console.log(Number.isFinite("42")); // false (a string, not a number)
console.log(Number.isInteger(10n)); // false (a bigint, not a number)
console.log(Number.isNaN(new Number(NaN))); // false (an object, not a primitive)Global isNaN and isFinite: The Coercing Versions
The global functions isNaN and isFinite came first. They run Number() on the argument and test the result. So they don't answer "is this NaN?" They answer "would this become NaN after conversion?" That is a different question, and the answers can surprise you.
console.log(isNaN("abc")); // true ("abc" converts to NaN)
console.log(isNaN("")); // false ("" converts to 0)
console.log(isNaN(undefined)); // true (undefined converts to NaN)
console.log(isFinite("42")); // true ("42" converts to 42)
console.log(isFinite(null)); // true (null converts to 0)
console.log(isFinite(" ")); // true (" " converts to 0)The next table puts the two families side by side.
| Input | `isNaN` | `Number.isNaN` | `isFinite` | `Number.isFinite` |
|---|---|---|---|---|
| `NaN` | true | true | false | false |
| `"abc"` | true | false | false | false |
| `""` | false | false | true | false |
| `"42"` | false | false | true | false |
| `null` | false | false | true | false |
| `undefined` | true | false | false | false |
| `Infinity` | false | false | false | false |
| `42` | false | false | true | true |
Look at the "" and null rows. If you check a form field with isFinite(value), an empty field passes as the number 0. Usually that is not what you want.
Other Ways to Detect NaN
NaN is the only JavaScript value that is not equal to itself. Two older idioms rely on that fact, and you will see them in existing code:
const x = 0 / 0;
console.log(x !== x); // true: only NaN fails self-equality
console.log(Object.is(x, NaN)); // true: SameValue treats NaN as equal to NaN
console.log([NaN].includes(NaN)); // true: includes uses SameValueZero
console.log([NaN].indexOf(NaN)); // -1: indexOf uses ===All of these work. Number.isNaN states the intent most clearly. The last two lines show something to watch for in array searches: indexOf can never find NaN, but includes can.
Number.isInteger: Checking the Stored Value
Number.isInteger checks the double that is actually stored. It does not look at what you typed in the source. Several edge cases follow from this.
console.log(Number.isInteger(5.0)); // true: 5.0 and 5 are the same value
console.log(Number.isInteger(-0)); // true
console.log(Number.isInteger(5.0000000000000001)); // true: the literal rounds to 5
console.log(Number.isInteger(1e300)); // true: huge doubles have no fraction bits left
console.log(Number.isInteger(Infinity)); // false
console.log(Number.isInteger((0.1 + 0.2) * 10)); // false: the result is 3.0000000000000004The last line is the important gotcha. If a value comes from floating-point arithmetic, it may sit a tiny distance from a whole number, and then isInteger correctly reports false. If you mean "close enough to an integer", round the value and compare with a tolerance:
function isNearlyInteger(x, epsilon = 1e-9) {
return Number.isFinite(x) && Math.abs(x - Math.round(x)) < epsilon;
}
console.log(isNearlyInteger((0.1 + 0.2) * 10)); // true
console.log(isNearlyInteger(2.5)); // falseChoose the tolerance to suit the size of your data. Number.EPSILON is the gap between doubles near 1. For values much larger than 1 it is too strict.
Number.isSafeInteger: Integers You Can Trust
Above 2 ** 53, doubles can no longer represent every integer, so 1e300 passes isInteger even though it stands for a whole range of nearby integers. Number.isSafeInteger adds a magnitude check. It returns true only when the value lies between -(2 ** 53 - 1) and 2 ** 53 - 1. In that range each double is exactly one integer and no neighboring integer rounds onto it.
console.log(Number.isSafeInteger(2 ** 53 - 1)); // true
console.log(Number.isSafeInteger(2 ** 53)); // false
console.log(Number.isSafeInteger(-(2 ** 53 - 1))); // true
console.log(Number.isSafeInteger(1e300)); // false
console.log(Number.isSafeInteger(3.0)); // true| Value | `isInteger` | `isSafeInteger` |
|---|---|---|
| `5` | true | true |
| `5.5` | false | false |
| `-0` | true | true |
| `2 ** 53` | true | false |
| `1e300` | true | false |
| `NaN` | false | false |
| `"5"` | false | false |
| `10n` | false | false |
Use isSafeInteger for IDs, counters, array indexes, and anything else you will compare for equality or add 1 to. If the check fails on data that is supposed to be integral, the data probably needs BigInt or a string representation. Don't try to repair the number.
Building a Validation Pipeline
These predicates only test numbers, so validating untrusted input takes two steps. First you convert the input. Then you check the result. The order of the checks matters.
function parseIntegerField(raw, { min = -Infinity, max = Infinity } = {}) {
if (typeof raw !== "string" || raw.trim() === "") {
return { ok: false, reason: "empty" };
}
const n = Number(raw);
if (!Number.isFinite(n)) {
return { ok: false, reason: "not a finite number" };
}
if (!Number.isSafeInteger(n)) {
return { ok: false, reason: "not a safe integer" };
}
if (n < min || n > max) {
return { ok: false, reason: "out of range" };
}
return { ok: true, value: n };
}
console.log(parseIntegerField("42", { min: 1, max: 100 })); // { ok: true, value: 42 }
console.log(parseIntegerField(" ")); // { ok: false, reason: "empty" }
console.log(parseIntegerField("12abc")); // { ok: false, reason: "not a finite number" }
console.log(parseIntegerField("2.5")); // { ok: false, reason: "not a safe integer" }
console.log(parseIntegerField("9007199254740993")); // { ok: false, reason: "not a safe integer" }
console.log(parseIntegerField("500", { max: 100 })); // { ok: false, reason: "out of range" }The empty-string check has to come first, because Number("") and Number(" ") both return 0. The "9007199254740993" case shows why the safe-integer check helps. Number() silently rounds that string to 9007199254740992, which is 2 ** 53. isSafeInteger rejects that value, so the precision loss never reaches your program.
Choosing the Right Check
| Question you are asking | Use |
|---|---|
| Is this value exactly `NaN`? | `Number.isNaN(x)` |
| Is this a usable number, not NaN or infinite? | `Number.isFinite(x)` |
| Does this number have no fractional part? | `Number.isInteger(x)` |
| Can I safely count, index, or compare it as an integer? | `Number.isSafeInteger(x)` |
| Is this whole integer within a tolerance after arithmetic? | `Math.round` plus a tolerance check |
| Would this string convert to a valid number? | `Number.isFinite(Number(s))`, after rejecting empty strings |
Exercise
A function validates a price with if (isFinite(input)) total += Number(input);. Name two inputs that pass the check but produce a wrong or surprising total, and rewrite the check.
Show answer
"" and null both pass, because isFinite converts them to 0. A whitespace-only string such as " " also passes. In each case the user never entered a price, but the code treats it as 0. A rewrite: const n = typeof input === "string" && input.trim() !== "" ? Number(input) : NaN; if (Number.isFinite(n)) total += n;
Exercise
Predict the output of Number.isInteger(1e21), Number.isSafeInteger(1e21), Number.isInteger("7"), and Number.isNaN("hello"), and explain each.
Show answer
true, false, false, false. The value 1e21 is a whole-valued double, so it is an integer, but it is far above 2 ** 53 - 1, so it is not safe. "7" is a string, and the Number.* predicates never convert strings. "hello" is also a string, not the number NaN, so Number.isNaN returns false even though Number("hello") would be NaN.
Exercise
Why does Number.isInteger(0.1 * 3 * 10) return false, and how would you test whether the result is "practically" an integer?
Show answer
0.1 * 3 is 0.30000000000000004, and multiplying by 10 gives 3.0000000000000004, which has a fractional part. To test whether it is close to an integer, use Math.abs(x - Math.round(x)) < epsilon with a tolerance suited to the size of the value, such as 1e-9, after first confirming Number.isFinite(x).