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);
// => 10

Internal 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:

  1. Defined Numbers: If both arguments are valid numbers, it returns their standard mathematical sum using native JavaScript arithmetic.
  2. Undefined Values: If an argument is undefined, Lodash treats it as the default value 0. For example, _.add(5, undefined) evaluates to 5.
  3. 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').
  4. Other Non-Numeric Types: Primitive values like null or boolean values are coerced according to JavaScript rules (e.g., null becomes 0, true becomes 1).

Why Use _.add Over the Native + Operator?

While a + b is sufficient for standard arithmetic, _.add is primarily used in functional programming patterns: