<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 a = obj?.a?.b?.c?.d
var a = _.get(obj, "a.b.c.d")
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
optional chaining | |
lodash get |
Test name | Executions per second |
---|---|
optional chaining | 13262487.0 Ops/sec |
lodash get | 2147394.0 Ops/sec |
Let's break down the provided benchmark and its test cases.
What is being tested?
The benchmark is comparing two approaches to perform optional chaining in JavaScript:
_.get()
for safely accessing nested properties of an object.Options compared
The two options being compared are:
_.get()
function from Lodash to achieve the same result.Pros and Cons of each approach
Optional Chaining (?.)
Pros:
Cons:
Lodash Get
Pros:
Cons:
Library: Lodash
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()
function is specifically designed to safely access nested properties of an object, handling cases where the property does not exist.
Special JS feature or syntax: None
There are no special JavaScript features or syntax used in this benchmark that require additional explanation.
Other alternatives
If you prefer not to use optional chaining, other alternatives for accessing nested properties include:
var a = obj && obj.a && obj.a.b && obj.a.b.c && obj.a.b.c.d
)in
operator and checking for existence before accessing the property (e.g., if ('a' in obj) if ('b' in obj.a) if ('c' in obj.a.b) if ('d' in obj.a.b.c) var a = obj.a.b.c.d
)However, these alternatives are generally less concise and expressive than optional chaining, and may require additional setup or configuration.