Came across the use while flipping through a book? At that time, I did not understand its usage, so I looked up some information.
? .
? The Cannot read property operator is an optional chain operator that can be used in development to access nested internal multilevel properties. This error causes the entire program to stop running, so we need to check whether each segment is undefined, for example:
var str = obj&&obj.objone&&obj.objone.objtwo
Copy the code
Verify that it is non-null and not undefined.
With optional chain calls, validation can be simplified and more secure:
var str = obj? .obj.objone? .obj.objone.objtwoCopy the code
By using? The. Operator replaces the. Operator. JavaScript implicitly checks to make sure that obj and obj.objone are neither null nor undefined before attempting to access obj.objone.objtwo. If null or undefined, the expression will short-circuit and return undefined without stopping the program. This is equivalent to the following expression, but does not actually create a temporary variable:
let temp = obj.objone;
let nestedProp = ((temp === null || temp === undefined) ? undefined : temp.objtwo);
Copy the code
Optional chains can also be used when trying to call a method that may not exist. If the called method does not exist when the function is called, using an optional chain causes the expression to automatically return undefined instead of throwing an exception.
let result = someInterface.customMethod? . ();Copy the code
let obj={ ice:function(){ console.log("hello") } } obj.ice? .() //=>helloCopy the code
Note: If an attribute name exists and is not a function, use? . A TypeError exception (x.y ‘ ‘is not a function) is still raised.
Note: If someInterface itself is null or undefined, If you want to allow someInterface to also be null or undefined, then you need to say someInterface, ok? .customMethod? . ()
Note:? . Arrays can also be accessed but cannot be used for assignment.
??
Null-value merge operator (not yet updated…)