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

    Quick tip about JavaScript's optional chaining operator

    People on twitter loved this trick I learned from a coworker's pull request the other day. You might like it too.

    You can use ?.() to call a potentially undefined function 🤯 Works for array access too. ?.[]

    The common use case for optional chaining is object access. If you're like me, that gave you the wrong mental model of the operator.

    const bird = {
      name: "Kiwi",
      species: ["Parrot"],
    }
    
    // prints undefined
    console.log(user.address?.street)
    

    If . is chaining, then ? is the optional part. Obvious.

    And wrong. ?. is the optional chaining operator for JavaScript.

    That gives you the flexibility to use it anywhere. Function calls, array access, ... I can't think of others.

    Optional chaining doesn't guarantee that what you're using supports the way you're holding it. Optional chaining is not a type check, it's an ergonomic way to hold null and undefined values.

    Best used in combination with TypeScript, which guarantees (ish) the correct type of underlying value. Like this:

    type Bird = {
      name: string
      species?: string[]
      address?: {
        continent: string
        environment: string
      }
    }
    
    const BirdButton = (props: { bird: Bird; onClick?: Function }) => {
      const { bird, onClick } = props
    
      return (
        <button onClick={() => onClick?.()}>
          {bird.name} is a {bird.species?.[0]} from the {bird.address?.environment}{" "}
          of {bird.address?.continent}
        </button>
      )
    }
    

    The ? in TypeScript types means "possibly undefined". The ?. in JavaScript lets you use that ergonomically. No more onClick && onClick() 😍

    You can use <BirdButton> all these ways:

    <BirdButton bird={{ name: "Kiwi" }} />
    
    <BirdButton bird={{ name: "Kiwi" }} onClick={() => alert("hai")} />
    
    <BirdButton bird={{ name: "Kiwi", species: ["Parrot", "Conure"] }} />
    
    <BirdButton
        bird={{
            name: "Kiwi",
            species: ["Parrot", "Conure"],
            address: { continent: "Brazil", environment: "Jungle" },
        }}
    />
    

    Browser and server environment support is good except you need the latest Safari and recent NodeJS.

    Optional chaining browser support
    Optional chaining browser support

    Not a concern, if you're using a build step in your code like Babel or TSC. Make sure you regularly update your browserlist because I hear Babel turns ?. into lots of code.

    Cheers,
    ~Swizec

    PS: yes my example doesn't do well with partial bird info. It prints Kiwi is a from the of. But that's not the point of this email 😅

    Published on April 22nd, 2022 in JavaScript, Quicktip

    Did you enjoy this article?

    Continue reading about Quick tip about JavaScript's optional chaining operator

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