How Lodash _.max Handles Empty Arrays

This article explains how the Lodash library's _.max method processes empty arrays, why it behaves differently from native JavaScript functions, and how developers can handle its output safely. You will learn the exact return value of _.max([]), the reasoning behind this design choice, and how to avoid common pitfalls in production code.

When passed an empty array, the Lodash _.max method evaluates the input and returns undefined. It does not throw an error, nor does it attempt to return a numeric boundary.

const _ = require('lodash');

const result = _.max([]);
console.log(result); // Output: undefined

Lodash is designed to provide predictable and safe defaults. If an input collection is empty, falsey, or contains no valid values to compare, returning undefined signals the complete absence of a maximum value. This avoids injecting arbitrary numbers into downstream application logic.

This behavior directly contrasts with native JavaScript's Math.max(). When using the spread operator with Math.max on an empty array, JavaScript evaluates Math.max() with zero arguments, which yields -Infinity:

const nativeResult = Math.max(...[]);
console.log(nativeResult); // Output: -Infinity

Receiving -Infinity can introduce subtle bugs, particularly when sorting, performing arithmetic, or formatting values for display. Lodash prevents this edge case by abstracting the boundary check internally.

Because _.max returns undefined for empty arrays, you should use optional chaining, nullish coalescing, or explicit checks when a fallback value is required:

const numbers = [];
const maxValue = _.max(numbers) ?? 0;

console.log(maxValue); // Output: 0

By returning undefined, _.max ensures that your application can explicitly detect missing data rather than inadvertently operating on -Infinity.