In JavaScript, we sometimes need to access properties of an object that might not even exist. Without careful checks, this can cause errors in our code.
Let’s say we have a post
object that usually has title
, description
, and author
, but in some cases, author
might be missing.
let post = {
title: "Learning JavaScript",
description: "A beginner's guide"
// author is missing!
};
Now, if we try to access author's name:
console.log(post.author.name); // ❌ Error: Cannot read property 'name' of undefined
We get an error because author does not exist, so trying to get name from it fails.
A Similar Example with DOM
If you're working with the DOM:
let html = document.querySelector('.elem').innerHTML;
If .elem does not exist, document.querySelector('.elem') will return null, and trying to access .innerHTML will throw an error as well.
How we used to handle this before Optional Chaining, we used conditional checks or the ternary operator:
console.log(post.author ? post.author.name : 'No author');
let elem = document.querySelector('.elem');
let html = elem ? elem.innerHTML : null;
This approach works, but it’s not very clean.
In some cases, we even end up calling the same function twice, for example:
let html = document.querySelector('.elem')
? document.querySelector('.elem').innerHTML
: null;
Optional Chaining to the Rescue
With Optional Chaining (?.), we can check properties in a cleaner and safer way.
console.log(post?.author?.name); // ✅ undefined (no error)
If post or author is null or undefined, it will simply return undefined and won’t throw an error.
The same works with DOM elements:
let html = document.querySelector('.elem')?.innerHTML;
If .elem is not found, html becomes undefined instead of crashing the script.
How It Works:
obj?.prop → Returns undefined if obj is null or undefined.
obj?.[expr] → Works for bracket notation.
obj?.method?.() → Works when calling methods that might not exist.
Final Thoughts Optional chaining helps you:
- Avoid long if / ternary checks.
- Prevent runtime errors when accessing nested properties.
- Write shorter, cleaner, and safer code.
- Once you start using it, you’ll probably never want to go back!
Thanks for checking out this article!