Optional Chaining (But reading this article is not optional…😉)

let user = {}; // a user without "address" propertyalert(user.address.street); // Error!
// document.querySelector('.elem') is null if there's no element let html = document.querySelector('.elem').innerHTML; // error if it's null
let user = {}; // user has no addressalert( user.address && user.address.street && user.address.street.name ); // undefined (no error)
let user = {}; // user has no addressalert( user?.address?.street ); // undefined (no error)
let user = null;alert( user?.address ); // undefined
alert( user?.address.street ); // undefined
// ReferenceError: user is not defined
user?.address;

Other variants: ?.(), ?.[]

let userAdmin = {
admin() {
alert("I am admin");
}
};
let userGuest = {};userAdmin.admin?.(); // I am adminuserGuest.admin?.(); // nothing (no such method)
let person1 = {
firstName: "John"
};
let person2 = null; // Imagine, we couldn't authorize the userlet key = "firstName";alert( person1?.[key] ); // John
alert( person2?.[key] ); // undefined
alert( person1?.[key]?.something?.not?.existing); // undefined
delete person?.name; // delete person.name if person exists

Summary

obj.val?.prop
obj.val?.[expr]
obj.arr?.[index]
obj.func?.(args)

--

--

--

Working as a full time Front-End developer & also searching web for some cool stuff.

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

Recommended from Medium

Jav-ing My Mind

Authentication and Authorisation with Node

https://youtu.be/63PnIpoCi2w

Solving Min Max

Future of Commerce AR using ARkit over the web

Rendering 3d offscreen: Getting max performance using canvas workers

9 Ultimate Tips to Optimise Angular Performance

DOM Manipulation: Intro to DOM

HTML static site

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
Abhishek Saxena

Abhishek Saxena

Working as a full time Front-End developer & also searching web for some cool stuff.

More from Medium

for(… in …) v/s for(… of ..)

Breakdown of the Asynchronous Promise: Fetch() Method

Why ‘Debounce’

Coding Space Invaders in JavaScript Complete Tutorial Every Step Explained with HTML5 Canvas