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',
}
};
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
}
This code can be minimized like below with the help of ?. operator
if(user.jobtitle?.name) {
// code related to use of user.jobtitle.name
}
Official Documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
checkout more such questions
Top comments (3)
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.
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".
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.