Optional Chaining & Nullish Coalescing

In es2019 and TypeScript 3.7 we got two new way to check nullish value(null, undefined), these are Optional Chaining & Nullish Coalescing.

Optional Chaining

Optional Chaining stops an expression whenever it encounters null or undefined. The syntax for the Optional Chaining is ?..

let user = {
  name: 'John Doe',
  address: {
    state: "California"

let userState = user ?. address ?. state
console.log(userState); // California

We defined user object, we checked if the user object has a property/key address then we checked the state key. This is equivalent as,

let userState = user && user.address && user.address.state;
console.log(userState); // California

What if any of the key has an empty value?

let user = {
  name: 'John Doe',
  address: {}

let userState = user ?. address ?. state;
console.log(userState); // undefined

We got undefined as expected. Let’s write it without Optional Chaining.

let userState = user && user.address && user.address.state
console.log(userState); // undefined; same result of Optional Chaining

Additionally we can do some more thing. We can extract the value of a specific index in an array.

function showFirstItem(arr) {
  return arr ?. [0];

console.log(showFirstItem([1, 2, 5])); // 1

So, the purpose of Optional Chaining is to avoid the deeply nested structure of if condition, in order to increase the readability.

Nullish Coalescing

This is very similar to || operator. In a given expression if the left side is not nullish it evaluates the left side, otherwise it evaluates right side. The syntax for Nullish Coalescing is ??.

let val = 0 ?? 9; // here 0 is a falsy value, so val should be 0

let res = null ?? 9; // here null is a nullish value, so res should be 9

The difference between || and ?? is ?? does consider falsy value(eg. “”, 0, false) a valid input where || doesn’t.

let val = "" ?? "JS"; // ""

let res = "" || "JS"; // "JS"

Leave a Reply

Your email address will not be published.