Strange syntax, what does `?.` mean in JavaScript?


Let’s try to understand ‘?.’ with an example.

Consider the following object example describing a male human being of age 23 −

const being = {
   human: {
      male: {
         age: 23
      }
   }
};

Now let’s say we want to access the age property of this being object. Pretty simple, right? We will just use chaining to access like the below code −

Example

const being = {
   human: {
      male: {
         age: 23
      }
   }
};
console.log(being.human.male.age);

Output

Console output is as follows −

23

Now let’s say you change the property male of being object to female or something else for some technical reasons.

Now what happens to our chaining statement, it will yield a typeError saying cannot access property undefined of human. Does there exist any way in such situations to make our code not throw any errors. Yes, and this is where ‘?.’ aka optional chaining comes to our rescue.

What optional chaining does is quite simple, it behaves like normal chaining in normal conditions but when we try to access any property off of undefined instead of making our code to throw an error, it terminates the chaining then and there and returns undefined so that the remaining chunk of code functions normally.

Consider our last example (optional chaining) −

Example

const being = {
   human: {
      male: {
         age: 23
      }
   }
}
console.log(being?.human?.female?.age);

Output

Instead of throwing the error, the output will be −

undefined

Updated on: 18-Aug-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements