About Me

About Me : I have been working as a Software Engineer for various international companies for four years.Currently, I am working as a full stack Javascript developer in Petronas(Malaysia).

Skills

Skills • Javascript •Typescript •Python •C •Java •ReactJs • Redux • VueJs • NestJs • React Testing Library • Django• PostgreSQL • MySQL • NodeJs • Git • Docker • Jira • Visual Studio Code • Slack

বৃহস্পতিবার, ১০ নভেম্বর, ২০২২

Optional chaining (?.) in Javascript

 

The optional chaining ?. is a safe way to access nested object properties, even if a mid   property doesn’t exist.

As an example, let’s say we have person objects and most of person have addresses in person.address property, with the street person.address.street, but some did not provide them.

In such case, when we attempt to get person.address.street without having street ,we get an error:

 

let person = {

}

 

console.log(person.address.street)

//error

 

 

As there is no address in person, an attempt to get person.address.street fails with an error.

But we if use optional chaining , we will get undefined instead of error.

 

console.log(person?.address?.street)  // undefined

 

In many practical cases we’d prefer to get undefined instead of an error here (meaning “no street”).

 

One case would be like this ,

 

let street = person?.address?.street ?? ' No street' ;