Lodash/Get
vs.
Babel Optional Chaining

David Lu

davidlu@m800.com

24 MAR 2022

@M800 Taiwan

// Example consider object
const obj = {
  a:{
     b:{
        c:'hello',
     },
  },
};





// Writing if conditions at each level
let value;
if (obj.a !== undefined && obj.a.b !== undefined && obj.a.b.c !== undefined) {
  value = obj.a.b.c;
} else{
  value = 'hello';
}
# Lodash/Get vs. Babel Optional Chaining

Overview

Q: How to get the value of "c" in object "obj"?

Overview

// Example using lodash get
import get from 'lodash/get';

const value = get(obj, 'a.b.c', 'hello');
const value = (obj.a?.b?.c ?? 'hello');

Lodash/Get

Babel Optional Chaining
(with nullish-coalescing-operator)

// Example consider object
const obj = {
  a:{
     b:{
        c:'hello',
     },
  },
};

Q: How to get the value of "c" in object "obj"?

# Lodash/Get vs. Babel Optional Chaining

Code Review (pt.1)

# Lodash/Get vs. Babel Optional Chaining

Ref: https://ext-gitlab.devops.maaii.com/cake/web/liveconnect-dashboard/-/merge_requests/3685

const {
  activeCallInfo,
} = props;

const entry = activeCallInfo?.executeRoom?.inquiry?.entry;
const status = activeCallInfo?.status;
const {
  activeCallInfo,
} = props;

// Example
const entry = get(activeCallInfo, 'executeRoom.inquiry.entry', '');
const status = get(activeCallInfo, 'status', '');

Original

Suggestion

Code Review (pt.2)

# Lodash/Get vs. Babel Optional Chaining

Ref: https://ext-gitlab.devops.maaii.com/cake/web/liveconnect-dashboard/-/merge_requests/3685

 ['tag', 'accessNumber', 'channel', 'email']
      .find((module) => entry?.[module]?.customChannelInfo?.enabled)
// Example
(module) => get(entry, `${module}.customChannelInfo.enabled`);

Original

Suggestion

Pros and Cons

  • Easy to install into existing project.
  • Library is pretty light weight.

👍🏻
Lodash/Get

  • No imports are required.
  • No additional library required at runtime.
  • Faster compared to Lodash.

👍🏻
Optional Chaining

# Lodash/Get vs. Babel Optional Chaining

Benchmark

# Lodash/Get vs. Babel Optional Chaining
// Script Preparation code:
var obj = {a: {b: {c: {d: 1}}}};
var badObj = {};

// Test: Optional Chaining
(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;

// Test: Lodash/Get
_.get(obj, "a.b.c.d", 2);
_.get(badObj, "a.b.c.d", 2);

Q: Value of "d" in object?

Test case name Executions per second
Optional Chaining 👍🏻 6601395.0 ops/sec
±0.67% (67 runs sampled)
Lodash/Get 2609358.0 ops/sec
±0.31% (65 runs sampled)
# Lodash/Get vs. Babel Optional Chaining

Benchmark

Result: https://measurethat.net/Embed?id=278131

Made with Slides.com