Member-only story
JavaScript: How Optional Chaining is going to change your code
Ever cursed your code when you had to make sure a nested property in a deep object exists? Curse no more!
Whenever you’re dealing with an object in JavaScript you often want to get data out of it. And when you want to get something out of an object that is nested a few layers deep you already fear the error “Cannot read property ‘name’ of undefined”, right? Sounds familiar?
Did you also curse when that error popped up in a production application?
Well, luckily there’s optional chaining. Let me explain
The backstory
Alright, so you got this object that might or might not have a certain data property, let’s say we’re dealing with a user. The data might look like this
It might, or might not have a name, and it might or might not have a first name property. So when you want to get this property you cannot trust the chain to exist, so what do you do? Right… check every level like this
And then once you’ve found the name property inside the user object exists, you can do something with the contents. And then you still don’t know exactly if there is a first name or not.
But what you rather would do would be this, right?
The Solution
Well, you’re in luck, that is exactly what optional chaining is here for. It will check, for you…