Lodash get Third Argument Default Values
The third argument in the Lodash _.get function
specifies a fallback value returned whenever the target path resolves to
undefined or does not exist. Developers can provide
virtually any valid JavaScript data type as this default value—including
strings, numbers, booleans, objects, arrays, functions, and even
null. This mechanism prevents runtime errors such as
TypeError: Cannot read property of undefined when
traversing deeply nested object structures.
Accepted Default Value Types
Lodash does not restrict the type of data you can pass as the third argument. Any valid JavaScript expression or value is permitted:
- Primitives: Strings, numbers, booleans, symbols,
and
null(e.g.,'N/A',0,false,null). - Complex Data Structures: Plain objects
(
{}), arrays ([]), sets, or maps to maintain a consistent schema for downstream processing. - Functions: Callbacks, no-op functions
(
() => {}), or factory functions. - Custom Instances: Class instances or custom prototypes.
Syntax and Basic Usage
const _ = require('lodash');
const user = {
profile: {
name: 'Alex'
}
};
// String default value
const role = _.get(user, 'profile.role', 'Guest');
// Output: 'Guest'
// Array default value
const permissions = _.get(user, 'profile.permissions', []);
// Output: []
// Object default value
const settings = _.get(user, 'settings.notifications', { email: true });
// Output: { email: true }When the Default Value Triggers
The default value is returned exclusively when the target property
evaluates to undefined. This happens under two
conditions:
- The path does not exist on the target object.
- The property explicitly holds the value
undefined.
Handling Falsy Values vs. Undefined
A common misconception is that the default value triggers for all
falsy values. Lodash strictly evaluates against undefined.
If a resolved property contains null, false,
0, NaN, or an empty string "",
Lodash returns that specific value rather than the default argument.
const config = {
retries: 0,
apiKey: null,
active: false
};
_.get(config, 'retries', 3); // Returns: 0 (not 3)
_.get(config, 'apiKey', 'secret'); // Returns: null (not 'secret')
_.get(config, 'active', true); // Returns: false (not true)
_.get(config, 'timeout', 5000); // Returns: 5000 (path does not exist)