JavaScript optional chaining (?.) to the rescue

I'm a full-stack developer from South Africa πΏπ¦. I love writing about JavaScript, HTML and CSS.
Search for a command to run...

I'm a full-stack developer from South Africa πΏπ¦. I love writing about JavaScript, HTML and CSS.
Awesome Yogesh, I'm a bit fan as well π Actually converted a lot of old codebase to ES6 just to use this π
Yeah such a blessing this is finally available π
Glad you like it Aiyush π
Most of you know me for my consistency, a golden arrow in my blog series. I've written 1000 articles in 1008 days! Almost an article a day, and my honeymoon was the only holiday I ever took. I'm super proud of this achievement; it has been a fantasti...

It's not the first time I'll be talking about community. I think it's an essential aspect of any successful tool. This shows in my previous explorations of Astro, Medusa, and now Vendure as well. All these products thrive in a super open, welcoming, ...

The cool part about Vendure is how easy it is to set up and how abstract each layer is. Basically, we get the following elements: External database Server Worker Admin UI Frontend While this is amazing, it also brings a bit of complexity when it co...

The previous article looked at customizing Vendure on a data and process level. In this article, we'll look at customizing emails, as they are often a big part of a webshop system. We'll be looking at two different layers of customization for customi...

Even though Vendure is a pretty significant project out of the box, in some cases, we might want to go in and modify some elements to work to our specific use case. In this article, I'll take a high-level look at some elements we can customize within...

Optional chaining has been added to the ES2020 version of JavaScript and is also available in TypeScript.
Optional chaining is a warmly welcomed way to access child properties, even when they don't exist!
Let's sketch a simple user object.
const user = {
firstName: 'Chris',
lastName: 'Bongers',
address: {
street: 'Some street',
},
};
Sometimes we can have a sub-object called shippingAddress, but it's not always required.
We could write code like this to check if it exists:
if (user.shippingAddress && user.shippingAddress.street) {
console.log(user.shippingAddress.street);
}
However, that will quickly get out of control if we need multiple properties from this shipping address object.
So let's see how optional chaining can come to our rescue here:
console.log(user.shippingAddress?.street);
That will now return undefined, as it is undefined, but won't throw an error.
The way this works is that it actually will evaluate the left-hand side of the question mark.
So in this example, it will evaluate if shipping exists or not.
It is pretty common to use optional chaining for object evaluation, but it can also be used in other forms.
One of these ways is the evaluate array-like calls so talking the example above, we could write code like this:
console.log(user.shippingAddress?.['street']);
This, in return, will evaluate on the same criteria but then call an array value instead of an object.
A third way of using optional chaining is to invoke functions but pass only if the object exists.
Let's say our shippingAddress object has a function called calculateShippingCost(), and we want to invoke that, but as you saw, sometimes, we don't even have the shipping address object.
Yes, that's another excellent use-case where optional chaining comes to our rescue.
user.shippingAddress?.calculateShippingCost();
// undefined
That, in turn, will return undefined again since the shipping address doesn't even exist.
Well, it's cool that we won't get errors anymore by calling properties of non-existing objects. Still, we rarely want to print out 'undefined', so let's see how we can use the JavaScript nullish coalescing operator to fix this issue.
For those who don't know, the nullish coalescing operator (??) is a logical operator.
It uses the following syntax:
evaluation ?? fallback;
Let's see it in action:
console.log(user.shippingAddress?.calculateShippingCost() ?? 'Free shipping');
What happens here is that we print out the calculate shipping function if the shipping address exists. However, if it doesn't, we return the fallback, which in this case prints out "Free shipping".
That's super helpful, right!
So what we learned today is that we can use optional chaining in JavaScript to evaluate if objects exist and to assess not them ourselves. As well as a way to return something more useful than undefined.
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter