How the Lodash _.add Method Handles Addition
This article provides an overview of the _.add method in
the Lodash JavaScript library, explaining its core syntax, internal
execution mechanism, type coercion behaviors, and common use cases in
functional programming.
The _.add method in Lodash is a mathematical utility
designed to add two numbers together. Its syntax accepts two arguments:
the augend (the first number) and the addend
(the second number).
import _ from 'lodash';
_.add(6, 4);
// => 10Internal Implementation
Under the hood, _.add is created using Lodash’s internal
createMathOperation wrapper. Instead of simply wrapping the
native JavaScript + operator without checks,
createMathOperation standardizes how missing or
non-standard numeric inputs are processed before performing the
addition.
When invoked, the function determines how to handle each operand:
- Defined Numbers: If both arguments are valid numbers, it returns their standard mathematical sum using native JavaScript arithmetic.
- Undefined Values: If an argument is
undefined, Lodash treats it as the default value0. For example,_.add(5, undefined)evaluates to5. - Strings and Type Coercion: If one of the operands
is a string, Lodash falls back on standard JavaScript type coercion,
converting the other operand to a string and performing string
concatenation (e.g.,
_.add('6', 4)returns'64'). - Other Non-Numeric Types: Primitive values like
nullor boolean values are coerced according to JavaScript rules (e.g.,nullbecomes0,truebecomes1).
Why Use
_.add Over the Native + Operator?
While a + b is sufficient for standard arithmetic,
_.add is primarily used in functional programming
patterns:
- Higher-Order Functions: Because
_.addis a named function rather than an operator, it can be passed directly as a callback without creating an inline arrow function:const numbers = [1, 2, 3, 4]; const sum = numbers.reduce(_.add, 0); // => 10 - Composition and Currying: Functional utility
libraries often curry functions or use them in pipelines (such as with
_.flowor Lodash FP). A standalone function allows addition to be composed cleanly alongside other transformations.