Wanna know what the differences between Number.isInteger()
, Number.isSafeInteger()
, and Number.isFinite()
? Check out the comparison table below.
As for which one you should use, it depends:
- You want to accept decimals and accept integers that are out of range =>
Number.isFinite()
- You want to reject decimals, but accept integers that are out of range =>
Number.isInteger()
- You want to reject decimals as well as reject integers that are out of range (see table below for out of range) =>
Number.isSafeInteger()
Number.isFinite()
is the least restrictive without permitting things you'd never accept as a number. Number.isSafeInteger()
is the most restrictive, which may or may not be the right choice for your use case.
Comparison table
They all reject Infinity
, BigInt
, and NaN
along with all the non-numeric types. The differences are highlighted:
Here's the code I used to create that table if you want to experiment:
const table = [
// From most negative to most positive
-Infinity,
Number.MIN_VALUE,
Number.MIN_SAFE_INTEGER,
-1.0000000000000001,
-1.000000000000001,
-1.59,
-1.0,
-1,
-0.1,
-0,
0,
0.1,
1,
1.0,
1.59,
1.000000000000001,
1.0000000000000001,
Math.pow(2, 53),
Math.pow(2, 53) - 1,
Number.MAX_SAFE_INTEGER,
Number.MAX_VALUE,
Infinity,
// Maybe?
BigInt(9007199254740991),
Number.EPSILON,
Math.PI,
// None of these are gonna pass
NaN,
'1',
null,
undefined,
false,
true,
[],
{}
].reduce((acc, val) => {
acc.push({
value: val,
'Number.isInteger()': Number.isInteger(val),
'Number.isSafeInteger()': Number.isSafeInteger(val),
'Number.isFinite()': Number.isFinite(val)
})
return acc
}, []);
console.table(table)
Discussion (0)