Lodash get Array Index Null Fallback Value
This article examines the behavior of the Lodash _.get
method when accessing an array index that evaluates to
null. It details how the library evaluates nullish array
elements, what value is returned when a default fallback is supplied,
and how to properly enforce a fallback when encountering
null.
In the Lodash JavaScript library,
_.get(object, path, [defaultValue]) only returns the
specified defaultValue if the resolved path resolves to
undefined. If an array index explicitly contains or
evaluates to null, Lodash considers null to be
a valid, resolved value rather than a missing property.
Consequently, no fallback value is returned; _.get will
return null directly.
Consider the following implementation:
const list = ['first', null, 'third'];
// Accessing index 1 which holds `null`
const result = _.get(list, 1, 'fallbackValue');
console.log(result);
// Output: nullEven though 'fallbackValue' was provided as the third
argument, the resolved value at index 1 is
null, not undefined. Because null
is an explicit primitive value indicating intentional absence, the
Lodash internal check (value === undefined) fails,
bypassing the fallback mechanism.
In contrast, targeting an array index that does not exist (such as
index 5) or an index holding an explicit
undefined will trigger the fallback:
// Accessing an out-of-bounds index
const outOfBounds = _.get(list, 5, 'fallbackValue');
console.log(outOfBounds);
// Output: 'fallbackValue'
// Accessing an undefined element
const listWithUndefined = ['first', undefined];
const undefinedResult = _.get(listWithUndefined, 1, 'fallbackValue');
console.log(undefinedResult);
// Output: 'fallbackValue'If your application requires a fallback value when an array index
evaluates to null, you must handle the nullish evaluation
explicitly outside of the _.get call using the nullish
coalescing operator (??) or the logical OR operator
(||):
const resultWithCoalescing = _.get(list, 1) ?? 'fallbackValue';
console.log(resultWithCoalescing);
// Output: 'fallbackValue'