Lodash _.divide Non-Numeric String Coercion
Lodash’s _.divide method processes mathematical division
by wrapping JavaScript’s native division operator within an internal
coercion pipeline. When passed non-numeric string objects, the function
does not crash or throw a runtime error; instead, it utilizes internal
casting utilities to resolve primitives, which ultimately yields
NaN according to standard ECMAScript numeric conversion
rules.
In the Lodash source code, _.divide is generated via an
internal helper factory called createMathOperation. This
factory governs how binary arithmetic methods handle inputs before
executing the core operation (dividend / divisor). The
factory assigns a fallback default value (typically 0) if
an argument is undefined, but dynamic objects and strings
bypass this fallback because they are considered defined values.
When a dynamic non-numeric String object (such as
new String("abc") or a string literal like
"foo") is passed into _.divide, Lodash
processes the input using an internal baseToNumber utility.
This utility checks the data type of the input:
- If the input is an object, JavaScript's built-in
valueOf()ortoString()method is invoked to extract the underlying primitive string value. - Lodash attempts to coerce the resulting primitive into a numeric
type using standard ECMAScript conversion (equivalent to applying the
unary
+operator or the abstractToNumberoperation). - Because the string contains non-numeric characters that cannot be
parsed into a valid float or integer, the conversion explicitly
evaluates to
NaN.
Once either the dividend or divisor resolves to NaN, the
native division operation executes. In standard JavaScript arithmetic,
any mathematical division involving NaN as an operand
automatically evaluates to NaN:
_.divide("abc", 2); // NaN
_.divide(10, new String("xyz")); // NaN
_.divide(new String("foo"), new String("bar")); // NaNUnlike some external parsing libraries that attempt to strip
non-numeric characters or use functions like parseFloat,
Lodash enforces strict numeric conversion. As a result, strings
containing trailing letters (such as "100px") will also
fail conversion and evaluate to NaN rather than partially
parsing to a number. Developers handling dynamic user inputs or
polymorphic objects must validate and sanitize strings prior to passing
them to _.divide to prevent NaN propagation
throughout their application state.