Comparing Dates and Timestamps with Lodash _.gte

Lodash’s _.gte function checks if a value is greater than or equal to another value. When comparing a JavaScript Date object against a strictly numeric timestamp, _.gte coerces the Date into its numeric millisecond equivalent using standard JavaScript type conversion. Because the function converts non-string operands to numbers before performing the relational comparison, developers can evaluate dates against epoch timestamps interchangeably and reliably without manually invoking .getTime().

The Under-the-Hood Coercion

In the source implementation of Lodash's _.gte, the function checks if both values are strings. If both values are not strings, it applies the unary plus operator (+) to coerce both arguments into numeric values:

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

When the unary + operator is applied to a Date instance in JavaScript, the engine calls Date.prototype.valueOf(). This returns the number of milliseconds elapsed since the Unix epoch (January 1, 1970, 00:00:00 UTC). The strictly numeric timestamp is already a primitive number, so +timestamp leaves its value unchanged.

Comparison Behavior and Order of Operands

The function evaluates the condition value >= other. The position of the arguments determines which entity is evaluated as the baseline:

Handling Invalid Dates

If a Date instance is invalid (for example, new Date('invalid')), coercing it with the unary + yields NaN.

In JavaScript relational comparisons, any operation comparing a number to NaN using >= returns false. Consequently:

const invalidDate = new Date('invalid');
const timestamp = 1767225600000;

_.gte(invalidDate, timestamp); // false
_.gte(timestamp, invalidDate); // false

When comparing dates against timestamps using _.gte, ensure that the Date objects represent valid calendar values to prevent unintended false results.