Lodash _.isInteger: Strict Whole Number Validation

The _.isInteger method in the Lodash JavaScript library provides a reliable way to verify whether a given value is a primitive whole number. This article explains the internal mechanics of _.isInteger, demonstrates how it handles type coercion and floating-point values, details its strict rejection of special numerical edge cases like NaN and Infinity, and contrasts it with standard JavaScript alternatives.

How _.isInteger Works

Lodash's _.isInteger(value) checks if a provided value is an integer. Under the hood, it performs strict validation without type coercion, meaning it will return true only if the input is fundamentally of the number type and represents a whole number without fractional components.

The underlying logic evaluates three main criteria:

  1. Type Checking: The input must have a typeof value of 'number', or be a number object wrapper that resolves to a primitive number without being null or undefined.
  2. Finiteness: The value must not be Infinity, -Infinity, or NaN.
  3. Integral Equality: The value must have no fractional remainder, mathematically equivalent to value % 1 === 0 or matching its floored counterpart.

Code Example and Common Validations

Unlike standard type conversion functions like parseInt, _.isInteger does not parse strings into numbers. It acts purely as a type guard.

const _ = require('lodash');

// Valid Integers
_.isInteger(4);           // => true
_.isInteger(-100);        // => true
_.isInteger(0);           // => true

// Decimals and Floats
_.isInteger(4.2);         // => false
_.isInteger(0.0001);      // => false

// Strict Type Checking (No Coercion)
_.isInteger('4');         // => false
_.isInteger(null);        // => false
_.isInteger(undefined);   // => false
_.isInteger([]);          // => false

// Special Numeric Values
_.isInteger(NaN);         // => false
_.isInteger(Infinity);    // => false
_.isInteger(-Infinity);   // => false

Distinction Between _.isInteger and _.isSafeInteger

_.isInteger validates whether a number is whole, but it does not restrict the number to the "safe" range defined by IEEE 754 double-precision floats. JavaScript can only safely represent integers between -(2^53 - 1) (Number.MIN_SAFE_INTEGER) and 2^53 - 1 (Number.MAX_SAFE_INTEGER).

Comparison With Native Number.isInteger()

In modern ECMAScript environments (ES6+), _.isInteger functions almost identically to the native Number.isInteger() method. Lodash includes this utility primarily for backwards compatibility with older runtimes, consistent chaining within the Lodash ecosystem, and safe handling of cross-realm objects (such as numbers created inside iframe environments where constructor checks might fail).