<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var obj = {a: {b: {c: {d: 1}}}}
var badObj = {}
(obj.a == null ? undefined : obj.a.b == null ? undefined : obj.a.b.c == null ? undefined : obj.a.b.c.d) || 2
(badObj.a == null ? undefined : badObj.a.b == null ? undefined : badObj.a.b.c == null ? undefined : badObj.a.b.c.d) || 2
_.get(obj, "a.b.c.d", 2)
_.get(badObj, "a.b.c.d", 2)
obj?.a?.b?.c?.d || 2;
badObj?.a?.b?.c?.d || 2;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Optional Chaining | |
Lodash | |
Optional Chaining v2 |
Test name | Executions per second |
---|---|
Optional Chaining | 6837154.0 Ops/sec |
Lodash | 2743307.5 Ops/sec |
Optional Chaining v2 | 13296500.0 Ops/sec |
I'll explain the benchmark and its results.
Benchmark Definition
The benchmark tests three approaches to access nested properties in an object:
?.
to safely navigate through nested objects, returning undefined
if any step fails..get()
method provides a safe way to access nested properties in an object, returning undefined
if any step fails.The benchmark also includes a comparison with the older syntax:
obj.a == null ? undefined : obj.a.b == null ? undefined : ...
) to navigate through nested objects.Options Compared
Pros and Cons of Each Approach
Library Used
Lodash is a popular utility library that provides various helper functions, including .get()
, for working with objects in JavaScript. In this benchmark, Lodash's .get()
method is used to access nested properties in an object.
Special JS Feature or Syntax
Optional Chaining (.?.
) is a new syntax introduced in ECMAScript 2020. It allows using ?.
to safely navigate through nested objects, returning undefined
if any step fails.
Other Alternatives
In summary, the benchmark tests three approaches to access nested properties in an object: Optional Chaining, Lodash's _.get() method, and the older syntax. The results show that Optional Chaining is the fastest approach, followed closely by Lodash's _.get() method, while the older syntax is slower due to its explicit checks.