DEV Community

Raushan Sharma
Raushan Sharma

Posted on • Edited on

JavaScript - Optional Chaining & Nullish Coalescing

Optional Chaining & Nullish Coalescing are coming to JavaScript! They're short and readable. Both these features are currently in stage 3, however we can start using the same with the help of following plugins that Babel provides:

@babel/plugin-proposal-optional-chaining
@babel/plugin-proposal-nullish-coalescing-operator

The optional chaining operator can be combined with the nullish coalescing ?? operator when a non-undefined default value is needed. This enables safe deep property access with a specified default value, addressing a common use case that previously required libraries such as lodash’s _.get:

const object = { id: 123, names: { first: 'Alice', last: 'Smith' }};

{ // With lodash:
  const firstName = _.get(object, 'names.first');
  // → 'Alice'

  const middleName = _.get(object, 'names.middle', '(no middle name)');
  // → '(no middle name)'
}

{ // With optional chaining and nullish coalescing:
  const firstName = object?.names?.first ?? '(no first name)';
  // → 'Alice'

  const middleName = object?.names?.middle ?? '(no middle name)';
  // → '(no middle name)'

}

Github:
https://github.com/tc39/proposal-nullish-coalescing
https://github.com/tc39/proposal-optional-chaining

V8.dev:
https://v8.dev/features/nullish-coalescing
https://v8.dev/features/optional-chaining

If you find the article informative, please don't forget to follow.

Happy coding :)

Interested in having a look at my other articles?

Learn some of the best practices in web accessibility that will help your web content or web application reach out to a broader audience.

If you talk optimization and walk optimization, memoization is one of the basic concepts that you must add in your skillsets. Moreover you will also learn how you can easily memoize your React components.

Learn how code splitting is a thing that you have been missing.

Top comments (0)