<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 = {}
((_c = (_b = (_a = obj === null || obj === void 0 ? void 0 : obj.a) === null || _a === void 0 ? void 0 : _a.b) === null || _b === void 0 ? void 0 : _b.c) === null || _c === void 0 ? void 0 : _c.d) || 2;
((_f = (_e = (_d = badObj === null || badObj === void 0 ? void 0 : badObj.a) === null || _d === void 0 ? void 0 : _d.b) === null || _e === void 0 ? void 0 : _e.c) === null || _f === void 0 ? void 0 : _f.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 |
---|---|
TS Optional Chaining result in javascript | |
Lodash Get | |
ES6 Optional Chaining |
Test name | Executions per second |
---|---|
TS Optional Chaining result in javascript | 2615206.2 Ops/sec |
Lodash Get | 588321.5 Ops/sec |
ES6 Optional Chaining | 18488162.0 Ops/sec |
This benchmark compares three ways to access nested properties in JavaScript objects: ES6 Optional Chaining, TypeScript Optional Chaining, and Lodash's _.get() function.
ES6 Optional Chaining
?.
) allows you to access nested properties of an object without causing a TypeError if any of the intermediate references are null or undefined. It is used as follows: obj?.a?.b?.c?.d
.TypeScript Optional Chaining
?.
). This is used in the context of JavaScript and is often used to ensure type safety at compile time. The implementation is similar to ES6 but with some additional checks.Lodash _.get()
_.get(obj, "a.b.c.d", 2)
.Special JS feature or syntax
None mentioned in this benchmark, but it's worth noting that ES6 Optional Chaining was introduced to provide a safe and concise way to access nested properties without causing errors. TypeScript's support for optional chaining provides additional type safety benefits.
Other alternatives
obj["a"]["b"]["c"]["d"]
) or the in
operator ("a" in obj && "b" in obj.a && "c" in obj.a.b && "d" in obj.a.b.c
). However, these methods can be less readable and may have higher overhead compared to optional chaining.