Lodash Math methods
What you’ll learn
- The 15 helpers in the Math category and how they cluster into arithmetic, rounding, and aggregation.
- Lodash’s nullish identity convention:
undefined→0foradd/subtract,1formultiply/divide. - How aggregation defaults (
_.max([])→undefined) are saner than nativeMath(which returns−Infinity). - How negative precision on
ceil/floor/roundsnaps numbers to tens, hundreds, and beyond. - When to reach for the
*Byvariants with an iteratee shorthand.
Prerequisites
Basic JavaScript numbers, the native Math object, and array iteration. Skip rows you already know; jump straight into the method index further down.
- Numbers & IEEE-754: awareness of floating-point quirks like
0.1 + 0.2 !== 0.3helps you appreciate the precision arguments onceil,floor, andround. - Native
Mathbasics: the difference betweenMath.max(a, b)(variadic) and_.max([a, b])(array input) is the most common source of bugs when switching. - Iteratee shorthand: the
*Byhelpers accept a property path string ("total") or a function. Comfort with that pattern unlocksmaxBy,sumBy, and friends. - Modules:
importfromlodash/methodNamein bundlers orrequire('lodash/methodName')in Node.js so install snippets match your project.
Key concepts
Three patterns repeat across all 15 helpers. Once you internalize them, the whole category reads quickly.
Nullish identity
_.add and _.subtract treat undefined as 0; _.multiply and _.divide treat it as 1. Safe inside _.reduce(arr, _.add).
Precision argument
Positive precision keeps decimals; negative precision rounds to tens/hundreds (_.round(4060, -2) → 4100).
Iteratee shorthand
The *By variants accept a property path ("price") or a function (x => x.qty * x.price) to project values before comparing or summing.
Overview
Lodash math helpers split into three clusters: pairwise arithmetic, precision rounding, and array aggregation. The first two are pure number-in / number-out; aggregators add an optional *By iteratee for object collections.
Arithmetic
add, subtract, multiply, divide — pairwise functions safe to use as reducer callbacks.
Rounding
ceil, floor, round with a precision argument that goes both directions (decimals or magnitudes).
Aggregation
max, min, sum, mean and their *By variants that accept an iteratee for object arrays.
⚖️ Lodash math vs native Math
Native Math covers single-value arithmetic. Lodash adds array-aware aggregators, precision arguments, and friendlier edge cases — without ever overriding the natives.
| Situation | Prefer native | Consider Lodash |
|---|---|---|
| Round to a fixed number of decimal places | Number(n.toFixed(2)) (string round-trip) | _.round(n, 2) — no string conversion, supports negative precision |
| Max of a known number of arguments | Math.max(a, b, c) | _.max(arr) when the values are already in an array |
| Aggregate by an object field | arr.reduce((m, o) => o.x > m ? o.x : m, -Infinity) | _.maxBy(arr, 'x') returning the whole object |
| Sum or average a numeric array | arr.reduce((a, b) => a + b, 0) | _.sum(arr), _.mean(arr) — intent is obvious at a glance |
Add two values that may be undefined | Manual ?? 0 on every operand | _.add already treats undefined as the additive identity |
Install and import
Install lodash once, then pull individual helpers so the bundler can tree-shake the rest.
npm install lodash import add from "lodash/add";
import round from "lodash/round";
import maxBy from "lodash/maxBy";
const subtotal = add(199, 25); // 224
const display = round(3.14159, 2); // 3.14
const winner = maxBy(
[{ name: "A", score: 88 }, { name: "B", score: 92 }],
"score"
);
// { name: "B", score: 92 } Friendlier defaults than native Math
The biggest reason to reach for lodash here is the edge cases. Empty arrays and missing operands behave predictably instead of returning ±Infinity or NaN.
import _ from "lodash";
// Aggregators on empty arrays
_.max([]); // undefined (Math.max() is -Infinity)
_.min([]); // undefined (Math.min() is Infinity)
_.sum([]); // 0
_.mean([]); // NaN
// Nullish identity in pairwise arithmetic
_.add(undefined, 5); // 5 (treats undefined as 0)
_.add(undefined, undefined); // 0
_.multiply(undefined, 2); // 2 (treats undefined as 1)
_.multiply(undefined, undefined); // 1
// Negative precision snaps to magnitudes
_.ceil(6040, -2); // 6100
_.floor(4060, -2); // 4000
_.round(4.006, 2); // 4.01 Suggested learning path
New to the Math category? Walk these in order — each one introduces a concept the next builds on.
- Pairwise arithmetic:
add,subtract,multiply,divide— learn the nullish identity rule first. - Rounding with precision:
round,ceil,floor— then try negative precision. - Array aggregation:
sum,mean,max,min— safe defaults baked in. - Iteratee variants:
sumBy,meanBy,maxBy,minBy— aggregate over object arrays.
💻 Environment and versions
- Lodash 4.x: this method list reflects the stable 4.x API, the same surface published as
lodash@^4on npm. - Node.js and browsers: one package for both; pick ESM (
import sum from "lodash/sum") in bundlers or CommonJS (require('lodash/sum')) in Node. - BigInt: the math helpers don’t mix with
BigInt. Convert withNumber(bigint)first if you can accept truncation, otherwise use native+,-on BigInts directly. - TypeScript: install
@types/lodashfor typings on namespace and per-method imports.
Method index
Each row links to a focused tutorial when it exists in this site. URLs follow the /lodash/math/{method-kebab} pattern (for example /lodash/math/max-by).
| Method | What it does |
|---|---|
_.add() | Add two numbers. Undefined operands are treated as 0. |
_.ceil() | Round a number up. Supports a precision argument, including negative precision. |
_.divide() | Divide two numbers. Undefined operands are treated as 1. |
_.floor() | Round a number down. Supports a precision argument, including negative precision. |
_.max() | Largest element in an array. Returns undefined when the array is empty. |
_.maxBy() | Like max, but each element is ranked by an iteratee (path or function). |
_.mean() | Arithmetic mean of an array of numbers. Returns NaN when the array is empty. |
_.meanBy() | Like mean, but each element is projected by an iteratee before averaging. |
_.min() | Smallest element in an array. Returns undefined when the array is empty. |
_.minBy() | Like min, but each element is ranked by an iteratee. |
_.multiply() | Multiply two numbers. Undefined operands are treated as 1. |
_.round() | Round a number. Supports precision; negative precision rounds to tens/hundreds. |
_.subtract() | Subtract the second number from the first. Undefined operands are treated as 0. |
_.sum() | Sum of an array of numbers. Returns 0 when the array is empty. |
_.sumBy() | Like sum, but each element is projected by an iteratee before adding. |
Pitfalls to avoid
Math.max(a, b) vs _.max([a, b])
Lodash aggregators expect a single array. Calling _.max(a, b, c) only inspects a and ignores the rest. Use the spread operator if you start from arguments: _.max([a, b, c]).
Different identities for + and *
_.add(undefined, undefined) is 0, but _.multiply(undefined, undefined) is 1. Choose the matching helper carefully when feeding sparse inputs.
Floating-point doesn’t go away
_.round can’t fix 0.1 + 0.2 === 0.30000000000000004. It just rounds the result you already got. Use BigInt or fixed-point integer arithmetic when money-level accuracy matters.
_.mean([]) is NaN
Only _.sum([]) short-circuits to 0. _.mean divides by zero, so guard with an explicit length check if you display the result to users.
❓ FAQ
Summary
- Scope: 15 helpers for arithmetic, rounding, and aggregation — with friendlier edge cases than native
Math. - Patterns: nullish identity, precision argument (positive or negative), and
*Byiteratee variants. - Next step: open Lodash _.add() or jump straight to any row in the method index above.
_.max([]) returns undefined — not −Infinity. Native Math.max() with no arguments returns −Infinity (and Math.min() returns +Infinity), which makes empty-collection edge cases noisy. Lodash flips that to a friendlier nullish.
7 people found this page helpful
