Lodash _.gt Type Coercion Rules Explained

Lodash's _.gt method checks whether a given value is greater than another, but its approach to type coercion differs significantly from native JavaScript relational operators. When evaluating two inherently incompatible types—such as a string and an object, or a string and a number—Lodash does not coerce values into strings. Instead, it enforces strict numeric coercion unless both operands are already primitives of type string.

The Underlying Evaluation Logic

Under the hood, Lodash implements _.gt with a strict type check before executing the comparison:

function gt(value, other) {
  if (!(typeof value === 'string' && typeof other === 'string')) {
    value = +value;
    other = +other;
  }
  return value > other;
}

Because of the condition !(typeof value === 'string' && typeof other === 'string'), lexicographical (string-based) comparison only occurs when both arguments are strictly strings. If at least one argument is not a string, Lodash bypasses string comparison entirely and attempts to convert both operands into numbers using JavaScript's unary plus (+) operator.

Numeric Coercion on Incompatible Types

When incompatible types are supplied, JavaScript’s abstract operation ToNumber is invoked on both arguments via +value and +other. This introduces specific coercion behaviors:

The Impact of NaN on Incompatible Comparisons

In JavaScript relational comparisons, any operation comparing a valid number to NaN—or NaN to NaN—evaluates to false. Because Lodash forces non-matching types through unary numeric conversion, comparing an unparseable string against another incompatible type inevitably produces NaN.

For example:

Differences from Native JavaScript Operators

In native JavaScript, comparing certain incompatible types with the > operator can yield unintuitive results because JavaScript might perform string coercion or primitive coercion depending on the operands. Lodash standardizes this behavior by ensuring that non-identical types never fall back to lexicographical string comparison. If two values cannot both be confirmed as strings, numeric evaluation is the only rule applied.