var obj = {a: {b: {c: {d: 1}}}}
var badObj = {}
var c = obj.a == null ? undefined : obj.a.b == null ? undefined : obj.a.b.c == null ? undefined : obj.a.b.c.d
c == null ? 2 : c
var d = badObj.a == null ? undefined : badObj.a.b == null ? undefined : badObj.a.b.c == null ? undefined : badObj.a.b.c.d
d == null ? 2 : d
_.get(obj, "a.b.c.d", 2)
_.get(badObj, "a.b.c.d", 2)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Optional Chaining | |
Lodash |
Test name | Executions per second |
---|---|
Optional Chaining | 94085704.0 Ops/sec |
Lodash | 6352210.5 Ops/sec |
I'll explain what's being tested in the provided benchmark.
Overview
The benchmark compares the performance of two approaches to access nested object properties: Optional Chaining (also known as nullish coalescing) and Lodash's _.get()
function.
Optional Chaining
This approach uses a chained comparison syntax (?.
) to safely navigate through the object hierarchy. The basic idea is to check if an object property exists before attempting to access it. If the property doesn't exist, the expression returns undefined
. To avoid this issue, Optional Chaining provides two additional operators:
?.
(optional chaining operator): Returns undefined
if any part of the chain is null
or undefined
.??
(nullish coalescing operator): Returns one value if the other is nullish (either null
or undefined
).In the benchmark, Optional Chaining is used to access nested object properties using the following syntax:
var c = obj.a == null ? undefined : obj.a.b == null ? undefined : obj.a.b.c == null ? undefined : obj.a.b.c.d
This expression checks each level of nesting before attempting to access the property, avoiding potential errors.
Lodash's _.get()
function
The Lodash library provides a utility function called _.get()
, which allows you to safely navigate through object hierarchies. The basic syntax is:
_.get(obj, 'a.b.c.d', 2)
This expression attempts to access the property at the specified path ('a.b.c.d'
) on the provided object (obj
). If any part of the path doesn't exist, it returns the default value (2
).
Pros and Cons
Optional Chaining:
Pros:
Cons:
Lodash's _.get()
function:
Pros:
Cons:
Other Considerations
_.get()
function might be more suitable due to its explicit error handling capabilities.Library and Syntax Explanation
The Lodash library provides the _.get()
function, which allows you to safely navigate through object hierarchies. This function takes three arguments:
obj
) to access.'a.b.c.d'
) to follow.The _.get()
function returns either the actual property value or the default value, depending on whether the path exists.
There is no special JavaScript feature or syntax being used in this benchmark aside from Optional Chaining and Lodash's _.get()
function.