The optional chain operator (? .). (1) Allow reading of the value of a property located deep in the chain of connected objects without explicitly validating that each reference in the chain is valid. (1) The function of the. Chain operator is similar to that of the. Chain operator, except that it does not raise an error if the reference is null (or undefined). When used with a function call, returns undefined if the given function does not exist.
If there is a nested object obj. When looking for a deeply nested child attribute without using an optional chain, you need to verify references between them, for example:letnestedProp = obj.first && obj.first.second; To avoid errors, before accessing obj.first.second, ensure that the value of obj.first is neithernull, nor is itundefined. 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 and then obtain the final result with short-circuit calculation before accessing obj.first.second. Such as:letnestedProp = obj.first? .second;Copy 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.