Lodash _.min Empty Array Return Value
This article examines the return value of the _.min
method in the Lodash JavaScript library when it is passed an empty
array. It details the exact output of this operation, contrasts it with
native JavaScript alternatives, and explains how to handle the result
safely in your applications.
The Return Value:
undefined
When you pass an empty array ([]) to Lodash's
_.min method, it returns undefined.
const _ = require('lodash');
const result = _.min([]);
console.log(result); // Output: undefinedLodash applies this behavior consistently across its collection and
math methods. If the provided array is empty, null, or
undefined, the method immediately returns
undefined without throwing an error.
Lodash _.min vs
Native Math.min
Lodash's implementation differs significantly from native JavaScript
behavior. When using the native Math.min() method with an
empty set of arguments (such as when spreading an empty array), the
return value is Infinity.
// Native JavaScript behavior
const nativeResult = Math.min(...[]);
console.log(nativeResult); // Output: InfinityMath.min() returns Infinity because it acts
as the identity value for minimum comparisons (any number compared to
Infinity is smaller). However, this often leads to
unintended logic errors in application development. Lodash returns
undefined to indicate that no minimum value exists within a
non-existent dataset, providing a more intuitive and safe result.
Handling the Output
Because _.min([]) evaluates to undefined,
you should provide a fallback value if your application expects a
numeric type. You can achieve this using the nullish coalescing operator
(??):
const data = [];
const minimumValue = _.min(data) ?? 0;
console.log(minimumValue); // Output: 0This ensures your code remains resilient against empty datasets
without unexpected NaN or Infinity
calculations down the line.