Swizec Teller - a geek with a hatswizec.com

Senior Mindset Book

Get promoted, earn a bigger salary, work for top companies

Senior Engineer Mindset cover
Learn more

    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.

    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.

    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

    Published on June 24th, 2021 in JavaScript, Technical

    Did you enjoy this article?

    Continue reading about A surprising feature of JavaScript optional chaining

    Semantically similar articles hand-picked by GPT-4

    Senior Mindset Book

    Get promoted, earn a bigger salary, work for top companies

    Learn more

    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

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