Lodash _.min: Empty Datasets and Fallbacks

In the Lodash JavaScript library, passing an empty or invalid dataset to the _.min function results in a safe return value of undefined rather than an error or an extreme numeric value. Because _.min does not accept a built-in fallback parameter, developers must handle absent values explicitly using post-processing techniques such as the nullish coalescing operator or Lodash’s own _.defaultTo method. This article explains how _.min evaluates empty inputs and details the standard approaches for applying custom default values.

How _.min Interprets Empty Datasets

When _.min(array) is called, the function first inspects the input collection. If the collection is empty ([]), null, undefined, or contains no valid comparable elements, _.min immediately returns undefined.

This design intentionally deviates from native JavaScript behavior in Math.min(). Calling Math.min() with no arguments or spreading an empty array (Math.min(...[])) yields Infinity. Lodash avoids this artifact by enforcing strict collection checks, treating an empty list as having no minimum element rather than an unbounded mathematical limit.

const _ = require('lodash');

console.log(_.min([]));        // undefined
console.log(_.min(null));      // undefined
console.log(_.min(undefined)); // undefined

Handling Fallback Values Explicitly

Because _.min does not provide an optional argument to specify a default return value, you must handle the returned undefined downstream.

1. Modern JavaScript Nullish Coalescing (??)

The cleanest approach in modern ECMAScript environments is the nullish coalescing operator (??). It replaces undefined with your chosen fallback while preserving legitimate zero (0) values, which an ordinary logical OR (||) would inadvertently overwrite.

const numbers = [];
const fallbackValue = 0;

const minimum = _.min(numbers) ?? fallbackValue;
console.log(minimum); // 0

2. Lodash _.defaultTo

If maintaining a pure Lodash pipeline or targeting older runtimes without transpilation, combine _.min with _.defaultTo. The _.defaultTo utility checks if a value is NaN, null, or undefined, returning the provided fallback when true.

const numbers = [];
const fallbackValue = -1;

const minimum = _.defaultTo(_.min(numbers), fallbackValue);
console.log(minimum); // -1

3. Custom Wrapper Functions

When repeatedly processing arrays across a codebase that require standardized default behavior, wrap _.min inside a custom helper function:

function safeMin(collection, defaultValue = null) {
  return _.min(collection) ?? defaultValue;
}

console.log(safeMin([]));       // null
console.log(safeMin([], 100));  // 100
console.log(safeMin([5, 2, 8])); // 2

By understanding that _.min yields undefined for empty inputs, you can prevent unexpected runtime behavior and safely map missing datasets to sensible fallbacks.