JavaScript code is executed line by line. If it raises any error, then stop execution.
If you are trying to access the object properties, if it exists, it returns the property otherwise, it will return undefined.
If you are trying to access the objects, if they exist, it returns the object otherwise, it will return an error (the next code is not executed to overcome this problem by using the optional changing concept.
Optional chaining symbol?
Optional chaining is introduced in ECMAScript 2020.
Optional chaining is a safe way to access nested object properties, even if the property doesn't exist.
Optional chaining ?. Stops the evolution of the value before ?. Is undefined or null and returns null.
Optional changing is recommended instead of logical && operators. Syntax: Nested object?. property
Different Solution to overcome the above problem :
Using the ternary operator:
var vysh = { }
console.log([vysh.info](<http://vysh.info/>) ? [vysh.info.name](<http://vysh.info.name/>): undefined )
Using logical && operators:
var vysh = { }
console.log([vysh.info](<http://vysh.info/>) && [vysh.info.name](<http://vysh.info.name/>) )
Note: It is fine, but it is not recommended for a large nested structure.
Optional chaining:
var vysh = {
info:{
name: 'shivaji'
}
}
console.log([vysh.info?.Name](<http://vysh.info/?.Name>) ) // trying to access declared object property
console.log(vysh.info12?.Name2 ) // trying to access the undeclared object property..