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 published ServerlessHandbook.dev avatarSwizec Teller published ServerlessHandbook.dev@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 over 14,000 engineers just like you already improving their careers with my letters, workshops, courses, and talks. ✌️

    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 over 14,000 engineers just like you already improving their careers with my letters, workshops, courses, and talks. ✌️

    Have a burning question that you think I can answer? I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

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

    Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.

    Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first 💰 on the side with ServerlessReact.Dev

    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 bySwizecwith ❤️