What is Optional Chaining in JavaScript?

Last Updated:
Golden chain against the sky

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

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.

Related Posts

Helpful Bits Straight Into Your Inbox

Subscribe to the newsletter for insights and helpful pieces on React, Gatsby, Next JS, Headless WordPress, and Jest testing.