What is Optional Chaining in JavaScript?

robmarshall

Robert Marshall

Posted on June 22, 2020

What is Optional Chaining in JavaScript?

I came across this way of retrieving values from JavaScript objects when I was looking for an alternative for the Lodash get function.

It allows you to conditionally access values from an object if they exist, and returns undefined rather than an error if not.

Consider this piece of code:

const cartoon = {
  name: 'Postman Page',
  helper: {
    animal: 'cat'
  }
};

const helperAnimal = cartoon.helper?.animal;
console.log(helperAnimal)
// expected output: cat

const helperName = cartoon.helper?.name;
console.log(helperName);
// expected output: undefined

Enter fullscreen mode Exit fullscreen mode

Rather that throwing an error when calling helperName, the question mark allows the key to be explored.

I find this incredibly helpful when you are not sure if a key/value exists, and donโ€™t want to break your piece of code.

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
robmarshall
Robert Marshall

Posted on June 22, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About