Cool syntax #1 | Optional chaining

daliboru

Dalibor Belic

Posted on May 8, 2021

Cool syntax #1 | Optional chaining

Welcome to the first post of the Cool Syntax series! I intend to publish a post, from time to time, on how to write clean JavaScript code like a pro!

The first text is about optional chaining. A syntactic sugar that makes reading content of an object much shorter and simpler. Let me show it to you.

Take a look at this array of objects.

const art = [
    {
        type: "paining",
        about: {
            name: "The starry night",
            author: "Vincent van Gogh",
            year: "1889",
            medium: "Oil on canvas",
        },
        dimensions: {
            width: "92.1",
            height: "73.7",
        },
    },
    {
        type: "sculpture",
        about: {
            name: "David",
            author: "Michelangelo",
        },
        dimensions: {
            width: "517",
            height: "199",
        },
    },
    {
        type: "photography",
        about: {
            name: "Pillars of Creation (Eagle Nebula)",
            author: "Hubble Space Telescope",
        },
    },
];
Enter fullscreen mode Exit fullscreen mode

Imagine we fetched some data, and now we have the art array of objects. Then, let's say we want to log type of each object in the art array.

art.forEach(artPiece => {
    console.log(artPiece.type);
})
Enter fullscreen mode Exit fullscreen mode

Now, let's log each height.

art.forEach(artPiece => {
    console.log(artPiece.dimensions.height);
})
Enter fullscreen mode Exit fullscreen mode

And... Yes, it will display the error message -> TypeError: Cannot read property 'height' of undefined. It's because we don't have the dimensions (on each object), and we're trying to get a property from it.

SOLUTION 1 - && operator

art.forEach(artPiece => {
    console.log(artPiece.dimensions && artPiece.dimensions.height);
})
Enter fullscreen mode Exit fullscreen mode

SOLUTION 2 - optional chaining

art.forEach(artPiece => {
    console.log(artPiece?.dimensions?.height);
})
Enter fullscreen mode Exit fullscreen mode

Imagine you have a complex object with many objects in objects...

w && w.x && w.x.y && w.x.y.z
vs
w?.x?.y?.z

I guess you see why optional chaining is the better solution (in terms of syntax)!

I hope you enjoyed this short syntax-related post! Check out my previous posts and stay tuned for more cool JavaScript stuff!

Cheers,
Dalibor

💖 💪 🙅 🚩
daliboru
Dalibor Belic

Posted on May 8, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Cool syntax #1 | Optional chaining
javascript Cool syntax #1 | Optional chaining

May 8, 2021