What is Optional Chaining in JavaScript? (2023)

By Geoff Griffiths @mmatraining1980

I asked Chat GPT to explain optional chaining in JavaScript to me like I’m 5:

Alright kiddo, imagine you have a big toy box. Inside this toy box, there are smaller boxes, and inside those, even smaller boxes. Some boxes might be empty, and others might have a toy or another smaller box inside.

Let’s say you want to find a tiny toy car, but you’re not sure which box it’s in. You start with the big toy box, then you open a smaller box inside, and then another one, and so on, until you either find the toy car or reach an empty box.

But there’s a problem. What if you try to open a box and there’s no box inside? You can’t keep looking, right? You’d stop there and say, “Oops! There’s no box here to open.”

In JavaScript, when you want to access something deep inside an object (like our big toy box), you might run into a similar problem. The thing you’re looking for might not be there, and if you try to access it, you’ll get an error.

JavaScript’s optional chaining is like a magic tool that helps with this. Instead of going box by box, and risking an error if something isn’t there, optional chaining lets you say, “Hey, if there’s a box here, open it. If not, that’s okay, just tell me there’s nothing there.”

In code, it looks like this:

let toy = bigToyBox?.smallBox?.tinyBox?.toyCar;

If any of the boxes don’t exist, JavaScript won’t get mad. It’ll just say undefined, meaning “I didn’t find it.” And that’s how optional chaining keeps our toy search safe and error-free!

Optional chaining is an operation in JS that let’s us access values, inside of an object.

Being able to use ?. – allows you to optionally chain things.

It will only try to access the nested value, if the first value existed.

if something doesnt’ exist – it will just return “undefined”

The optional chaining is helpful when working with a database and lots of data, so that you don’t have to manage a load of “if statements”

Optional chaining is a convenient way to access values inside of objects, when working with dynamic data its important that you avoid errors and crashing. Optional chaining can help with this!