Lodash _.subtract with JavaScript Date Objects

This article explains how Lodash’s _.subtract method processes time differences when provided strictly with JavaScript Date instances. It explores the underlying type coercion mechanisms, the role of native JavaScript methods, and why this approach delivers optimal execution speed when calculating durations between dates.

The Inner Workings of Lodash _.subtract

Lodash implements _.subtract using an internal helper called createMathOperation. At its core, the function is essentially a wrapper around JavaScript's native subtraction arithmetic operator:

const subtract = createMathOperation((minuend, subtrahend) => minuend - subtrahend, 0);

When two arguments are passed to _.subtract, Lodash relies on standard JavaScript type conversion rather than explicitly checking for Date instances or calling date-specific methods like .getTime().

Implicit Date Coercion via valueOf()

When the native subtraction operator (-) evaluates two operands, it forces both operands to convert into primitive numeric values.

JavaScript Date instances have a built-in Date.prototype.valueOf() method, which returns the timestamp of the date as an integer representing milliseconds since the Unix Epoch (January 1, 1970, 00:00:00 UTC). During evaluation:

  1. _.subtract(dateA, dateB) invokes dateA - dateB.
  2. The JavaScript engine encounters objects in an arithmetic expression and invokes their [Symbol.toPrimitive]('number') or valueOf() methods.
  3. Both dates are converted into their respective millisecond values in place.
  4. The engine subtracts the two integers and returns the difference in milliseconds.
const dateA = new Date('2026-03-30T12:00:00Z');
const dateB = new Date('2026-03-30T10:00:00Z');

const differenceInMs = _.subtract(dateA, dateB);
// Returns: 7200000 (2 hours in milliseconds)

Why This Mechanism Is Efficient

Processing date differences through _.subtract is efficient due to the following factors:

Considerations

Because the result is always an integer representing milliseconds: