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:

Number.isInteger(value)
  • value: The value to be tested.

Return Value:

  • Returns true if the value is an integer; otherwise, it returns false.

Key Characteristics:

  1. 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.

  2. 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

console.log(Number.isInteger(5)); // true console.log(Number.isInteger(-3)); // true console.log(Number.isInteger(0)); // true

In these examples, 5, -3, and 0 are all integers, so the function returns true.

Example 2: Non-integer Values

console.log(Number.isInteger(3.14)); // false console.log(Number.isInteger(-1.5)); // false console.log(Number.isInteger(Math.PI)); // false

In these cases, the values 3.14, -1.5, and Math.PI are not integers, resulting in false.

Example 3: Non-numeric Values

console.log(Number.isInteger("10")); // false console.log(Number.isInteger(true)); // false console.log(Number.isInteger(undefined)); // false console.log(Number.isInteger(null)); // false

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.

console.log(Number.isInteger(NaN)); // false

Example 5: Special Cases

  • Infinity and -Infinity: These values are also not integers.
console.log(Number.isInteger(Infinity)); // false console.log(Number.isInteger(-Infinity)); // false

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) and false 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.