DEV Community

Robert Marshall
Robert Marshall

Posted on • Originally published at robertmarshall.dev on

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay