Basics
Number.isInteger()
Checks that a value is a whole number — and actually a number.
Why it exists
Data often comes from outside: a form, a server, a file. Anything can show up there — the string "5", a fraction 2.5, null. If the program expects a whole number (item quantity, page number, age), it's better to check right away. Number.isInteger answers two questions in one check: "is it a number?" and "is it whole?".
Where it's used
- The quantity of an item in a cart: you can't buy 2.5 phones.
- A page number or ID from the address bar.
- Server-side validation: age, year, number of seats.
- Game cells and grid coordinates — like the digits in the sudoku challenge.
Syntax
Number.isInteger(value)Examples
Number.isInteger(5); // → true
Number.isInteger(5.5); // → false
Number.isInteger("5"); // → false
Number.isInteger(null); // → falseNumber.isInteger(5.0); // → true — it's the same number as 5
Number.isInteger(NaN); // → false
Number.isInteger(Infinity); // → falsefunction isValidQuantity(q) {
return Number.isInteger(q) && q > 0;
}
isValidQuantity(3); // → true
isValidQuantity(0); // → false
isValidQuantity(1.5); // → false
isValidQuantity("3"); // → falseconst fromForm = "42";
Number.isInteger(fromForm); // → false
Number.isInteger(Number(fromForm)); // → trueResults after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
Number.isInteger(x) returns true only if x is already of type number and has no fractional part. It doesn't convert anything: the string "5" isn't a number, so the answer is false.
NaN and Infinity aren't integers either, even though technically they're of type number.
There's a catch with notation: 5.0 in JavaScript is the same number as 5, so it's an integer. The language has no separate "integer" type — isInteger checks the value itself.
Traps
How it differs from…
- Comparison:
===,!==,<,> Comparisons (
>= 0,<= 9) check the range;Number.isIntegerchecks the type and wholeness. Validation usually needs both, joined with &&.
When to pick something else
If fractions are allowed (price, weight, rating), you need "it's a number and not NaN": typeof x === "number" && !Number.isNaN(x), not isInteger.