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

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay