How Lodash multiply Evaluates Boolean Arguments

This article explains the internal mechanics behind Lodash's _.multiply method when handling strictly boolean parameters. It covers how Lodash abstracts arithmetic operations through internal wrapper functions, how arguments are processed, and how JavaScript's native type coercion rules seamlessly convert boolean values into numeric operands to calculate valid mathematical products.

The Higher-Order Wrapper: createMathOperation

Lodash does not implement multiplication directly inside _.multiply. Instead, it defines the method using an internal factory function called createMathOperation:

const multiply = createMathOperation((multiplier, multiplicand) => multiplier * multiplicand, 1);

The createMathOperation utility acts as a safeguard and pre-processor for binary arithmetic calculations. When _.multiply is invoked, this wrapper intercepts the arguments before applying the actual multiplication callback. It performs checks for undefined parameters, applies default fallbacks, and normalizes argument types.

Argument Normalization and baseToNumber

When _.multiply(true, false) is called, the inputs reach the type-checking phase inside createMathOperation. The function determines whether either argument is a string (which triggers string concatenation behavior in operations like addition). Because neither operand is a string, the values are routed through numeric conversion routines, typically referencing baseToNumber or direct numeric parsing depending on the Lodash version.

Lodash’s internal conversion checks if the input is already a primitive or an object, stripping wrappers and attempting to resolve the primitive value into a standard JavaScript number.

Underlying JavaScript Coercion (ToNumber)

Even when parameters bypass explicit transformation within Lodash's source, the underlying binary expression multiplier * multiplicand triggers JavaScript’s native abstract operation: ToNumeric (or ToNumber in older ECMAScript specifications).

Under the ECMAScript specification:

When the callback (multiplier, multiplicand) => multiplier * multiplicand executes:

Handling Non-Standard Boolean Invocations

If only one boolean argument is supplied, such as _.multiply(true), Lodash's createMathOperation checks for undefined arguments. If other is undefined, it returns the first argument directly without applying the mathematical callback. In that specific scenario, _.multiply(true) returns the primitive boolean true rather than 1, because the arithmetic operation is never executed against the second parameter. When both parameters are supplied, full numeric coercion is enforced, producing a predictable numeric outcome.