Lodash find Return Value When No Match Is Found
When searching through collections in JavaScript using the Lodash
utility library, understanding the default behavior of search methods is
essential for avoiding runtime errors. This article explains the exact
execution fallback returned by _.find when no element
satisfies the predicate, demonstrates how it behaves through code
examples, and covers best practices for safely handling the resulting
value.
The Execution Fallback:
undefined
If the predicate function in _.find iterates through the
entire collection and does not successfully match any element, the
execution fallback returned by the method is
undefined.
Lodash does not throw an error or return null,
false, or -1; it strictly returns the
primitive value undefined.
const _ = require('lodash');
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
// Searching for a non-existent user
const result = _.find(users, { name: 'Charlie' });
console.log(result);
// Output: undefinedHandling the
undefined Fallback
Because the fallback is undefined, attempting to access
properties directly on the result without validation will result in a
TypeError: Cannot read properties of undefined.
You can handle the undefined fallback using several
standard JavaScript and Lodash techniques:
1. Optional Chaining
(?.)
Optional chaining allows you to safely read nested properties without causing a runtime exception if the item was not found.
const user = _.find(users, { id: 99 });
const userName = user?.name; // Evaluates to undefined instead of throwing an error2. Nullish Coalescing
(??)
If your application requires a default fallback object or value, use the nullish coalescing operator:
const defaultUser = { id: 0, name: 'Guest' };
const user = _.find(users, { id: 99 }) ?? defaultUser;3. Lodash _.defaultTo
Lodash provides a built-in helper to substitute
undefined (or NaN/null) with a
default value:
const user = _.defaultTo(_.find(users, { id: 99 }), { id: 0, name: 'Guest' });Potential
Pitfall: Collections Containing undefined
A common edge case occurs when searching an array that explicitly
contains undefined values:
const list = [1, 2, undefined, 4];
const result = _.find(list, (item) => item === undefined);In this scenario, _.find returns undefined
because the element was successfully located, not because the search
failed. If your logic needs to distinguish between "element not found"
and "element found with value undefined", use _.findIndex
or _.some instead:
const exists = _.some(list, (item) => item === undefined);
// Returns true, confirming the value exists in the array