JavaScript Number.isInteger(value) function
The Number.isInteger(value)
function in JavaScript is a static method that determines whether the provided value is an integer. This method is part of the Number
object and provides a reliable way to check for integer values without type coercion.
Syntax:
value
: The value to be tested.
Return Value:
- Returns
true
if the value is an integer; otherwise, it returnsfalse
.
Key Characteristics:
No Type Coercion: Unlike the global
parseInt()
function,Number.isInteger()
does not coerce the argument into a number. It checks the value as it is, ensuring accurate type checking.Definition of Integer: An integer is a whole number that can be positive, negative, or zero, but it cannot have a fractional component.
Example 1: Basic Usage
In these examples, 5
, -3
, and 0
are all integers, so the function returns true
.
Example 2: Non-integer Values
In these cases, the values 3.14
, -1.5
, and Math.PI
are not integers, resulting in false
.
Example 3: Non-numeric Values
Here, non-numeric values such as strings, booleans, and null
do not count as integers, so the function returns false
.
Example 4: Using with NaN
The behavior of Number.isInteger()
with NaN
is noteworthy since it will return false
.
Example 5: Special Cases
- Infinity and -Infinity: These values are also not integers.
Summary:
- The
Number.isInteger(value)
function checks if a value is an integer without converting it to a number type. - It returns
true
for whole numbers (positive, negative, and zero) andfalse
for non-integers,NaN
, and non-numeric values. - This method is useful for validating numeric inputs where you want to ensure the value is an integer before performing operations.