current position:Home>Optional chain operator (?.) And null merge operators (?)[ es2020]

Optional chain operator (?.) And null merge operators (?)[ es2020]

2021-08-27 10:31:04 Chen__

I came across the use of ?. Chain access to objects , I didn't know how to use it at that time , So I looked up some information .


?. Is an optional chain operator , It is used to deal with accessing multi-level attributes nested inside in development , There may be a mistake Cannot read property... This kind of reporting is wrong , Make the whole program stop running , Therefore, it is necessary to judge whether each paragraph is undefined, Such as :

var str = obj&&obj.objone&&obj.objone.objtwo
 Copy code 

Confirm non null It's not undefined.

With optional chained calls , It can simplify the verification operation , And safer :

var str = obj?.obj.objone?.obj.objone.objtwo
 Copy code 

By using  ?.  The operator replaces  .  The operator ,JavaScript Will be trying to access  obj.objone.objtwo  Before , Implicitly check and determine  obj and obj.objone  neither  null  Neither  undefined. If it is  null  perhaps  undefined, The expression will be short circuited directly back to  undefined, Will not stop the program . This is equivalent to the following expression , But you don't actually create a temporary variable :

let temp = obj.objone;
let nestedProp = ((temp === null || temp === undefined) ? undefined : temp.objtwo);
 Copy code 

Optional chains can also be used when trying to call a method that may not exist . When a function is called, if the called method does not exist , Using an optional chain allows the expression to automatically return undefined Instead of throwing an exception .

let result = someInterface.customMethod?.();
 Copy code 
let obj={
	} //=>hello
 Copy code 

Be careful :   If there is a property name and it is not a function , Use  ?.  There will still be a  TypeError  abnormal (x.y`` is not a function).

Be careful :   If  someInterface  Is itself  null  perhaps  undefined , abnormal  TypeError  Will still be thrown out  someInterface is null  If you want to allow  someInterface  Also for the  null  perhaps  undefined , So you need to write like this  someInterface?.customMethod?.()

Be careful :?. Arrays can also be accessed, but not used for assignment .


Null merge operator ( Not yet updated ...)

copyright notice
author[Chen__],Please bring the original link to reprint, thank you.

Random recommended