Number.isInteger
You'll learn how to reliably check if a value is a whole number using Number.isInteger.
What Is Number.isInteger?
Number.isInteger is a built-in method that tells you whether a value is an integer (a whole number with no fractional part). It returns true only if the value is both a number and a whole number. Otherwise, it returns false.
How It Works
Think of Number.isInteger as a strict gatekeeper. It checks two things:
- Is it a number at all? (Not a string, boolean, null, etc.)
- Is it a whole number? (No decimal portion)
Only when both conditions are met does it return true.
Number.isInteger(42); // true
Number.isInteger(0); // true
Number.isInteger(-5); // true
Number.isInteger(3.14); // false (has decimal)
Number.isInteger(5.0); // true (no fractional part)
Number.isInteger('100'); // false (it's a string)
Number.isInteger(true); // false (it's a boolean)
Number.isInteger(null); // false (not a number)
Number.isInteger(undefined); // false (not a number)
Number.isInteger(NaN); // false (NaN is not an integer)
Number.isInteger(Infinity); // false (not finite)
Why This Matters
Unlike checking typeof value === 'number', which only tells you if something is some kind of number, Number.isInteger specifically identifies whole numbers. This is crucial when you need to validate counts, array indices, or any scenario where fractional values don't make sense.
Key Takeaway: Number.isInteger returns true only for actual whole numbers; it returns false for non-numbers, decimals, NaN, and Infinity.