People on twitter loved this trick I learned from a coworker's pull request the other day. You might like it too.
TIL this works #javascript pic.twitter.com/l4wtDypkC5
— Swizec Teller (@Swizec) April 20, 2022
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.
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 😅
Continue reading about Quick tip about JavaScript's optional chaining operator
Semantically similar articles hand-picked by GPT-4
- A surprising feature of JavaScript optional chaining
- Why null checks are bad
- TypeScript's biggest flaw and how you can use ducks to fix it
- Learn TypeScript in 5 minutes
- How JavaScript linters cause bugs
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.
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 ❤️