var obj = {a: {b: {c: {d: 1}}}}
(obj.a == null ? undefined : obj.a.b == null ? undefined : obj.a.b.c == null ? undefined : obj.a.b.c.d) || 2
_.get(obj, "a.b.c.d", 2)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Optional Chaining | |
Lodash |
Test name | Executions per second |
---|---|
Optional Chaining | 3294327.2 Ops/sec |
Lodash | 2277426.5 Ops/sec |
What is being tested:
MeasureThat.net is testing two different approaches to access nested properties in an object:
??
) and chaining comparison operators (==
, ===
) to safely navigate through the object's structure.Options compared:
The benchmark compares two options:
Pros and Cons of each approach:
??
)Library:
Lodash is a popular JavaScript utility library that provides a wide range of functions for tasks such as string manipulation, array operations, and more. The _.get()
method is specifically designed to safely access nested properties in an object.
Special JS feature or syntax:
The benchmark uses the nullish coalescing operator (??
), which was introduced in ECMAScript 2020 (ES2020). This operator allows you to safely navigate through objects, avoiding null pointer exceptions. If you're not familiar with this operator, it's a new addition to modern JavaScript and is supported by most modern browsers and JavaScript engines.
Other alternatives:
If you prefer not to use Optional Chaining or Lodash's _.get() method, you can consider the following alternatives:
[]
) to access nested properties. For example, obj['a']['b']['c']
..
) and null checks (&&
) to access nested properties. For example, (obj.a && obj.a.b && obj.a.b.c)
.However, these alternatives may not be as concise or efficient as Optional Chaining or Lodash's _.get() method.