DEV Community

Heru Hartanto
Heru Hartanto

Posted on

2 2

Optional Chaining ?.

Chaining operator will give us undefined when reference that we want to use is nullish instead of error, it's very usefull when the content of an object don't have guarantee as to which properties are required

const ourObject = {
    name:'Alina',
    pet:{
        name:'kitty',
        type:'cat'
    }
}
const dogName = ourObject.dog.name;
console.log(dogName)
Enter fullscreen mode Exit fullscreen mode

Because dog is not exist at ourObject then it will return Uncaught TypeError: Cannot read property 'name' of undefined

To prevent those error we can use optional chaining, so instead of error this code will return undefined

const dogName = ourObject.dog?.name
console.log(dogName)
// Undefined
Enter fullscreen mode Exit fullscreen mode

It also work for checking methods inside object

console.log(ourObject.nonEksistingMethod())
//Uncaught TypeError: ourObject.someNonExistentMethod is not a function

console.log(ourObject.someNonExistentMethod?.())
// Undefined    
Enter fullscreen mode Exit fullscreen mode

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more