DEV Community

Cover image for Cool syntax #1 | Optional chaining
Dalibor Belic
Dalibor Belic

Posted on

3 2

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

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

11 Tips That Make You a Better Typescript Programmer

typescript

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

đź‘‹ Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay