preface
The optional chain operator (? .). Allows you to read the value of a property located in the chain of linked objects without explicitly validating that each reference in the chain is valid. The difference is that an error is not raised when the reference is null (or undefined), and the expression shorts out the return value of undefined. When used with a function call, returns undefined if the given function does not exist.
The optional chain operator makes the expression root shorter and more concise when trying to access object properties that may not exist. The optional chain operator is also helpful when exploring the contents of an object if it is not certain which attributes must exist.
describe
The optional chain operator provides a way to simplify access to the value of the connected object via a reference to the connected object or when the function may be undefined or NULL.
For example, consider an object obj with a nested structure. When looking for a deeply nested child attribute without using an optional chain, you need to verify references between them, for example:
let nestedProp = obj.first && obj.first.second
Copy the code
To avoid errors, before accessing obj.first.second, ensure that the value of obj.first is neither null nor undefined. If you simply access obj.first.second directly without checking obj.first, an error may be thrown.
With the optional chain operator (? .). , it is no longer necessary to explicitly verify the state of obj.first before accessing obj.first.second and then obtain the final result with short-circuit calculation:
let nestedProp = obj.first? .secondCopy the code
By using? The. Operator replaces the. Operator. JavaScript implicitly checks to make sure obj.first is neither null nor undefined before attempting to access obj.first.second. If obj.first is null or undefined, the expression will short-circuit the evaluation and return undefined directly.
This is equivalent to the following expression, but no temporary variable is actually created:
let temp = obj.first
let nestedProp = ((temp === null || temp === undefined) ? undefined : temp.second)
Copy the code
Source: Optional chain operator