When Does Lodash get Return the Default Value?

This article examines how the _.get method in the Lodash JavaScript library handles default fallback parameters when encountering falsy values. While JavaScript recognizes several distinct falsy evaluations—including false, 0, "", null, NaN, and undefined—Lodash enforces strict criteria for deploying the fallback value. Understanding these specific boundaries is crucial for avoiding unexpected bugs in data retrieval and state management.

The Only Trigger: undefined

In Lodash, the default fallback parameter of _.get(object, path, [defaultValue]) is triggered exclusively when the resolved value at the specified path evaluates to undefined.

If a property does not exist on the object, JavaScript resolves that lookup to undefined, which subsequently deploys the default value. Similarly, if the property explicitly exists and its value is set to undefined, the fallback will still be returned.

How Lodash _.get Treats Other Falsy Values

Lodash does not treat generic falsy values as missing data. If the resolved path evaluates to any falsy value other than undefined, _.get will return that falsy value directly and ignore the default parameter.

The behavior for each JavaScript falsy value is as follows:

Code Demonstration

const _ = require('lodash');

const data = {
  a: undefined,
  b: null,
  c: false,
  d: 0,
  e: '',
  f: NaN
};

const fallback = 'DEFAULT';

_.get(data, 'a', fallback); // Returns: 'DEFAULT' (triggered)
_.get(data, 'missingKey', fallback); // Returns: 'DEFAULT' (triggered)

_.get(data, 'b', fallback); // Returns: null
_.get(data, 'c', fallback); // Returns: false
_.get(data, 'd', fallback); // Returns: 0
_.get(data, 'e', fallback); // Returns: ''
_.get(data, 'f', fallback); // Returns: NaN

Summary

The only falsy evaluation that deploys the default fallback in _.get is undefined. All other falsy values (null, false, 0, "", and NaN) are treated as resolved, intentional data points and will bypass the default argument.