Optional chaining: ‘?.’

let user = {}; // a user without "address" propertyalert(user.address.street); // Error!
let user = {};alert(user.address ? user.address.street ? user.address.street.name : null : null);
let user = {}; // user has no addressalert( user.address && user.address.street && user.address.street.name ); // undefined (no error)

Optional chaining

  • is the same as value.prop if value exists,
  • otherwise (when value is undefined/null) it returns undefined.
let user = {}; // user has no address

alert( user?.address?.street ); // undefined (no error)
// ReferenceError: user is not defined
user?.address;

Summary

  1. obj?.prop – returns obj.prop if obj exists, otherwise undefined.
  2. obj?.[prop] – returns obj[prop] if obj exists, otherwise undefined.
  3. obj.method?.() – calls obj.method() if obj.method exists, otherwise returns undefined.

--

--

--

Developer with 3 yrs of industrial experience in developing scalable web applications.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Destructuring in JavaScript

Requestly Turns 6!

Functional Programming In JavaScript: TypeScript for Beginners

The difference between Props & State

Lambda Calculus with JavaScript

How To Generate an Alphabet JavaScript Array

Building A Super Cool Colorful Logger with Deno | Deno By Example

NgRx — Cherry Picking the Meta

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abhay Jain

Abhay Jain

Developer with 3 yrs of industrial experience in developing scalable web applications.

More from Medium

ESlint, Prettier, EditorConfig and Husky For react typescript Project

Clean Code with ESLint

Minimal Setup for Typescript + HTML5 Development

What is a framework?