Lodash _.isFinite vs Native isFinite in JavaScript
This article explains the critical differences between Lodash's
_.isFinite method and JavaScript's global native
isFinite function. While both functions check whether a
value is a finite number, they handle data types and type coercion
fundamentally differently, leading to contrasting results when
processing non-numeric inputs.
The Core Difference: Type Coercion
The primary distinction between the two functions lies in how they handle non-number values:
- Native global
isFinite()coercively converts its argument to a number before evaluating whether it is finite. - Lodash's
_.isFinite()does not coerce values. It strictly checks whether the provided input is both of the typenumberand finite.
Because native isFinite() converts values using standard
JavaScript type coercion rules, values that are not numbers—such as
numeric strings, booleans, empty arrays, and null—can
evaluate to true.
Comparison with Code Examples
Here is how both functions behave across various data types:
// Numeric values
isFinite(42); // true
_.isFinite(42); // true
isFinite(Infinity); // false
_.isFinite(Infinity); // false
isFinite(NaN); // false
_.isFinite(NaN); // false
// Strings
isFinite("42"); // true (coerced to 42)
_.isFinite("42"); // false (not a number primitive)
isFinite(""); // true (coerced to 0)
_.isFinite(""); // false
isFinite("hello"); // false (coerced to NaN)
_.isFinite("hello"); // false
// Null and Booleans
isFinite(null); // true (coerced to 0)
_.isFinite(null); // false
isFinite(true); // true (coerced to 1)
_.isFinite(true); // false
isFinite(false); // true (coerced to 0)
_.isFinite(false); // false
// Objects and Arrays
isFinite([]); // true (coerced to 0)
_.isFinite([]); // false
isFinite([10]); // true (coerced to 10)
_.isFinite([10]); // falseRelationship to ES6
Number.isFinite
With the release of ECMAScript 2015 (ES6), JavaScript introduced
Number.isFinite(). This method addressed the flaws of the
global isFinite() by omitting type coercion.
Lodash’s _.isFinite behaves almost identically to
Number.isFinite(), returning true only for
primitive values where typeof value === 'number' and the
value is not Infinity, -Infinity, or
NaN.
Summary
The global native isFinite() checks if a value can
be converted into a finite number, whereas Lodash's
_.isFinite checks if a value already is a finite
number. When strict type safety is required, _.isFinite (or
modern JavaScript's Number.isFinite) prevents unexpected
false positives caused by implicit type casting.