DEV Community

Passionate Coder
Passionate Coder

Posted on

Javascript Interview Questions : Optional chaining (?.)

1) What is chaining operator?
Ans ) According to MDN official docs, The optional chaining operator (?.) permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid

Note : The optional chaining ?. stops the evaluation if the value before ?. is undefined or null and returns undefined.

2) In which version of Javascript optional chaining is intoduced?

Ans ) ECMAScript 2020

3) Example

lets we have one object like below

const user = {
  name: 'Test User',
  address: {
    city: 'mumbai',
  }
};
Enter fullscreen mode Exit fullscreen mode

if we try to access user.address.city => We will get mumbai but if we access something like this

user.jobtitle.name => this will gives as error as jobtitle is not a property of user and we are trying to access name property of undefined so earliar to ?. operator we need to do something like below to avoid this kind of error

if(user.jobtitle && user.jobtitle.name) {
   // code related to use of user.jobtitle.name
}
Enter fullscreen mode Exit fullscreen mode

This code can be minimized like below with the help of ?. operator

if(user.jobtitle?.name) {
  // code related to use of user.jobtitle.name
}
Enter fullscreen mode Exit fullscreen mode

Official Documentation

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

checkout more such questions

Top comments (3)

Collapse
 
xr0master profile image
Sergey Khomushin

The second question is relevant if you are looking for a history teacher. No, seriously, what are you checking here? But we can take this topic and ask how to implement the optional chaining operator logic on older versions.

Collapse
 
jlitowitz profile image
Jason Litowitz

Knowing in which version the operator got introduced is useful to more than just a history teacher. For example, say you take over a system running Node 12. That doesn't run ECMAScript 2020, so using this operator would break. This is a brand new operator, so until the supporting runtime is guaranteed - or at least, a likelihood - it's important to know such details. At a minimum, for such a new operator, you should be able to answer, "a really recent version".

Collapse
 
xr0master profile image
Sergey Khomushin

I doubt you check every feature, is there any support for your engine? Everyone should mind their own business, and for this there are compilers. I suggest you get to know Babel.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.