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.
TIL you can use optional chaining on function calls 🤯 pic.twitter.com/rfjw5A5atn
— Swizec Teller (@Swizec) June 23, 2021
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.
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
Continue reading about A surprising feature of JavaScript optional chaining
Semantically similar articles hand-picked by GPT-4
- Quick tip about JavaScript's optional chaining operator
- Async, await, catch – error handling that won't drive you crazy
- How JavaScript linters cause bugs
- A cool JavaScript property you never noticed
- How GraphQL blows REST out of the water
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 ❤️