JSL: ES2020 Optional Chaining Operator...explained with cats
Optional Chaining. It looks like a question mark next to a period, but there's a lot of hidden power in that punctuation.
It's also known as the ternary conditional operator because it combines some of what the ternary operator does together with the chaining operator, normally called dot notation.
It's similar to the traditional dot syntax which lets you access an object and its properties.
Say you have a list of cats you need to keep track of. You might have some data that looks like this to track them.
const cats = [
You can use dot notation to get to the fur color. That would look like this:
const myColor = cats.fur.color;
// returns 'calico'
But what if in your list of animals, you have a cat that has no fur?
const cats = [
The problem here is that JSON data, specially when working with a NoSQL database doesn't necessarily return all of the fields, so we can't guarantee that we'll have a fur object available.
In that case, you'd get an error from the compiler. And it's not one of those easy to find errors. It's one of those that implies you're an idiot.
You can try fixing it by using the ternary operator like this:
const myColor = (cats.fur.color) ? cats.fur.color : '';
What we're doing here is a short version of an if...then statement. First, we test for the cats color and if it's undefined or null, then return an empty string, which is similar. But honestly, that's not the most readable code.
The Optional Chaining operator performs this test for you.
const myColor = cats.body?.fur.color
If the fur object doesn't exist, it will return undefined instead of null so you don't get the error. That's also much easier to read. Ternary statements are awesome, but they always give me a headache.
So make sure you're using a transpiler like Babel if you want this to work in older browsers.
Learn more about Optional Chaining on MDN.