Replace lodash.get with Optional Chaining Syntax

Share this video with your friends

Send Tweet

This lesson will demonstrate how to replace common uses of lodash.get with optional chaining syntax.

_.get is by far my favorite lodash method. I've been on so many projects where the results of a network call was a large and often unreliable blob of data. After countless attempts to reign in errors caused by trying to access non-existent properties I've come to rely on _.get as a simple & safe way to retrieve data from those objects. However, as is always the case in web development, times are changing and the tools we need to safely access properties of complex objects are now being built into the platform. Optional chaining syntax gives us the power of _.get without several of the tradeoffs. It doesn't require an extra library to use, it plays nicely with TypeScript and it can be used when calling methods as well as when accessing properties.

This lesson covers 4 common use cases of lodash.get and converts them to using optional chaining syntax.

  1. Nested Object and Array Access
  2. String and Variable Property Access
  3. Calling a Method on an Object that may Not Exist
  4. Providing a Default Value when a Property does Not Exist

Resources