<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
obj?.a?.b?.c?.d || 2
badObj?.a?.b?.c?.d || 2
_.get(obj, "a.b.c.d", 2)
_.get(badObj, "a.b.c.d", 2)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
ES5 Optional Chaining | |
ES6 Optional Chaining | |
Lodash Get |
Test name | Executions per second |
---|---|
ES5 Optional Chaining | 34254436.0 Ops/sec |
ES6 Optional Chaining | 31376830.0 Ops/sec |
Lodash Get | 1563903.4 Ops/sec |
Let's break down the provided benchmark and its test cases.
Benchmark Definition
The benchmark measures the performance of three different approaches for accessing nested properties in JavaScript objects:
??
) to access nested properties.?.
) to access nested properties._.get()
, which is designed for safely accessing nested properties in objects.Options Compared
The three options are compared in terms of their execution speed and performance.
Pros and Cons
Here's a brief summary of each approach:
Library Used
The benchmark uses the Lodash library, version 4.17.5, which provides the _.get()
function for safely accessing nested properties in objects.
Special JS Feature/Syntax
Only ES6 Optional Chaining uses a special JavaScript feature/syntax, specifically the optional chaining operator (?.
). This feature was introduced in ECMAScript 2017 (ES2017) and is supported by modern browsers, including Firefox 85. The other two approaches do not use this syntax.
Alternative Approaches
Other approaches for accessing nested properties in objects include:
obj.a && obj.a.b && obj.a.b.c
)obj['a'] && obj['a']['b'] && obj['a']['b']['c']
)However, these alternative approaches may have different trade-offs in terms of performance, conciseness, and readability compared to the three options being measured in this benchmark.