How Lodash get Safely Resolves Deep Properties
The _.get method in Lodash allows developers to safely
retrieve values from deeply nested objects without triggering
TypeError: Cannot read properties of undefined or
null. Historically, accessing deeply nested properties in
standard JavaScript posed a significant risk of runtime crashes whenever
an intermediate property was missing. Lodash eliminates this problem by
normalizing property paths, traversing the target object step-by-step,
validating intermediate states against null or
undefined, and returning a default value if the target
property cannot be resolved.
The Problem with Native Nested Access
In traditional JavaScript, accessing a property like
user.profile.address.city fails fatally if any intermediate
property—such as profile or address—evaluates
to null or undefined. Attempting to read a
property on a nullish value causes the JavaScript engine to throw a
TypeError, halting script execution.
Path Normalization
When you provide a path to _.get, it accepts either an
array of keys (e.g., ['a', 'b', 'c']) or a string
representation (e.g., 'a.b.c' or
'a[0].b.c').
Lodash processes this path using an internal helper function
(historically toPath or castPath). If the path
is a string, Lodash uses regular expressions to parse and split it into
an array of individual property keys and array indices. Lodash also
maintains an internal cache for compiled string paths, ensuring that
repeatedly queried path strings avoid the performance overhead of
redundant regex parsing.
Iterative Traversal
Once the path is converted into an array of segments, Lodash iterates through the keys sequentially using a standard loop rather than recursion.
- Initialization: Lodash sets a pointer (the current context) directly to the target object.
- Step-by-Step Traversal: For each key in the normalized path array, the function reads the corresponding property from the current context and updates the pointer to hold that value.
- Guard Checking: At each iteration, Lodash verifies
that the current context is not
nullorundefined.
Early Exit and Nullish Safety
If at any point during iteration the intermediate context becomes
null or undefined, Lodash immediately breaks
out of the loop. Because it never attempts to access a property on an
intermediate nullish value, no native TypeError is thrown.
The iteration terminates gracefully, and the traversal pointer is
evaluated as undefined.
Default Value Handling
After the loop finishes—either because the full path was successfully traversed or because traversal halted early—Lodash checks the final result:
- If the resolved value is explicitly
undefined,_.getreturns the user-provided default value (orundefinedif no default was specified). - If the resolved value is any other falsy value (such as
null,false,0, or""), Lodash preserves and returns that value, treating it as a valid, successfully resolved property.