Node.js Optional chaining operator allows reading the value of a property located deep inside a chain of connected objects without having to expressly validate each reference in that chain. This operator functions similarly to the chaining operator, except that instead of causing an error if a reference is null or undefined, the expression returns a value of UNDEFINED. It also returns the same if used with a function call and the given function does not exists.
Why it is useful? Well good question it actually results in shorter and simpler expressions when accessing chained properties when there is a possibility that a reference may be missing. It also can be helpful while exploring content of an object when there is no known guarantee as to which properties are required.
This cannot be used on a non-declared root object, but can be used with an undefined root object.
EXAMPLE WITH CHAIN OF OBJECTS
Let us consider an example where an object (obj) which has nested structure. Now without optional chaining looking up a deeply-nested sub property requires validation of the references in between, like:
//Let nestedProp = obj.first && obj.first.second; (code)
The value of the obj.first is confirmed to be not-null and not-undefined before then accessing the value of obj.first.second. This prevents the error that would show if you accessed obj.first.second directly without accessing its parent object obj.first.
With optional chaining, however we do not have to explicitly test and short-circuit based on the state of the parent object i.e., object.first before trying to access obj.first.second:
//let nestedProp = obj.first?.second; (code)
By using this operator java script knows to implicitly check the state of object.first before attempting to access the obj.first.second. If the parent object is null or undefined the expression automatically returns undefined.
This Addition is really helpful to multiple developers, I find it interesting (personal preference).
For more details visit: