Swizec Teller - a geek with a hatswizec.com

    A surprising feature of JavaScript optional chaining

    In 2020 JavaScript gained a new feature – optional chaining. It solves a problem we've had ... forever. With many workarounds and standard solutions over the years.

    Swizec Teller in 🇸🇮 avatarSwizec Teller in 🇸🇮@Swizec
    TIL you can use optional chaining on function calls 🤯
    Tweet media

    The problem optional chaining solves

    You get an object like this:

    const object = {
    greet: "hai",
    deepProp: {
    greet: "hello",
    deeperProp: {
    greet: "ohai",
    },
    },
    }

    JSON response from an API or reading from a database. Perhaps a blob you've built up on the frontend.

    How do you access the 3rd level greet, if object, deepProp, and deeperProp might be undefined?

    You could rely on JavaScript's evaluation semantics. Last value from expression is returned.

    const greeting =
    object &&
    object.deepProp &&
    object.deepProp.deeperProp &&
    object.deepProp.deeperProp.greet

    Confusing for newbies, annoying to write, easy to get wrong. Exploding complexity to boot.

    A clearer way to write that are conditionals:

    let greeting = undefined
    if (object) {
    if (object.deepProp) {
    if (object.deepProp.deeperProp) {
    greeting = object.deepProp.deeperProp
    }
    }
    }

    Clearer, more verbose, nobody writes this in production code. Feels weird to use conditionals for assignment. 🤷

    Another common approach is to use a library like Lodash:

    const greeting = _.get(object, "deepProp.deeperProp.greet")

    Personally not a fan. Feels unnecessary.

    Curated JavaScript Essays

    Get a series of curated essays on JavaScript. Lessons and insights from building software for production. No bullshit.

    Join 15,883+ engineers learning lessons from my "raw and honest from the heart" emails.

    ⭐️⭐️⭐️⭐️✨
    4.5 stars average rating

    Use optional chaining

    With optional chaining you can do this natively:

    const greeting = object?.deepProp?.deeperProp?.greet

    😍

    You've probably seen that before. Everyone's been very excited after wishing this existed for 10+ years.

    But you might've missed that the operator is ?., not ?. This is important because you can optionally chain anything 🤯

    Function calls:

    object?.deepProp?.function?.(args)

    Array access:

    object?.deepProp?.deepArray?.[5]

    And even expressions:

    object?.deepProp?.[console.log("runs if deepProp defined")]

    Please don't use that last one 😅

    Cheers,
    ~Swizec

    Did you enjoy this article?

    Published on June 24th, 2021 in JavaScript, Technical,

    Want to become a JavaScript expert?

    Learning from tutorials is great! You follow some steps, learn a smol lesson, and feel like you got this. Then you go into an interview, get a question from the boss, or encounter a new situation and o-oh.

    Shit, how does this work again? 😅

    That's the problem with tutorials. They're not how the world works. Real software is a mess. A best-effort pile of duct tape and chewing gum. You need deep understanding, not recipes.

    Leave your email and get the JavaScript Essays series - a series of curated essays and experiments on modern JavaScript. Lessons learned from practice building production software.

    Curated JavaScript Essays

    Get a series of curated essays on JavaScript. Lessons and insights from building software for production. No bullshit.

    Join 15,883+ engineers learning lessons from my "raw and honest from the heart" emails.

    ⭐️⭐️⭐️⭐️✨
    4.5 stars average rating

    Have a burning question that you think I can answer? Hit me up on twitter and I'll do my best.

    Who am I and who do I help? I'm Swizec Teller and I turn coders into engineers with "Raw and honest from the heart!" writing. No bullshit. Real insights into the career and skills of a modern software engineer.

    Want to become a true senior engineer? Take ownership, have autonomy, and be a force multiplier on your team. The Senior Engineer Mindset ebook can help 👉 swizec.com/senior-mindset. These are the shifts in mindset that unlocked my career.

    Curious about Serverless and the modern backend? Check out Serverless Handbook, for frontend engineers 👉 ServerlessHandbook.dev

    Want to Stop copy pasting D3 examples and create data visualizations of your own? Learn how to build scalable dataviz React components your whole team can understand with React for Data Visualization

    Want to get my best emails on JavaScript, React, Serverless, Fullstack Web, or Indie Hacking? Check out swizec.com/collections

    Want to brush up on modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

    Did someone amazing share this letter with you? Wonderful! You can sign up for my weekly letters for software engineers on their path to greatness, here: swizec.com/blog

    Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

    By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️

    Created by Swizec with ❤️