Lodash _.gt String Comparison Explained

The _.gt method in the Lodash JavaScript library determines whether a given value is strictly greater than another. When working with strings, _.gt diverges in behavior depending on whether both arguments are strings or if a string is being compared against a different data type. This article breaks down how Lodash processes string inputs, how it evaluates lexicographical order, and how type coercion alters comparison results.

String vs. String Comparisons

When both arguments passed to _.gt(value, other) are strings, Lodash relies on JavaScript's native greater-than (>) relational operator. In this scenario, strings are compared lexicographically according to standard UTF-16 / ASCII code point values rather than numeric magnitude or character length.

const _ = require('lodash');

// Lexicographical comparison
_.gt('banana', 'apple'); // true (because 'b' comes after 'a')
_.gt('apple', 'banana'); // false

// Alphabetical order vs. numeric string order
_.gt('2', '10'); // true (compares character '2' to character '1')

Because comparisons are based on Unicode values, case sensitivity plays a critical role:

_.gt('a', 'B'); // true (lowercase 'a' has code point 97, 'B' has code point 66)
_.gt('Apple', 'apple'); // false ('A' has code point 65, 'a' has code point 97)

Mixed-Type Comparisons and Numeric Coercion

If either operand is not a string, Lodash applies a strict type-coercion rule. Internally, Lodash checks if both operands are of type 'string'. If that condition fails, it coerces both operands into numbers using JavaScript's unary plus operator (+value).

The internal logic functions like this:

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

String and Number Comparison

When a numeric string is evaluated against an actual number, the string is converted to a number before the comparison occurs:

_.gt('10', 2); // true ('10' is coerced to 10; 10 > 2)
_.gt(20, '5'); // true ('5' is coerced to 5; 20 > 5)

Non-Numeric Strings and NaN

If a string cannot be parsed into a valid number and is compared against a non-string value, the unary plus coercion results in NaN. In JavaScript, any relational comparison involving NaN evaluates to false:

_.gt('hello', 5); // false ('hello' coerces to NaN; NaN > 5 is false)
_.gt(5, 'hello'); // false ('hello' coerces to NaN; 5 > NaN is false)

Summary of Rules

  1. Both values are strings: Lodash conducts a standard character-by-character Unicode code point comparison.
  2. One value is a string and the other is not: Both values are converted to numbers via +. Numeric strings are parsed to their numeric values, while non-numeric strings become NaN, resulting in false.