<>??: Null merge operator
Logical operator , On the left null and undefined Hour , To return the number on the right const sum = null ?? 12 console.log(sum);
// output 12 const sum1 = 12 ?? 23 console.log(sum1); // output 12 const sum2 = undefined ??
12 console.log(sum2); // output 12
<>?. : Optional chain operator
You can read the values of attributes located deep in the chain of connected objects , It is not necessary to explicitly verify that each reference in the chain is valid
Functions similar to “.” Chained operator , The difference is , Empty in reference null perhaps undefined Will not cause an error , The short circuit return value of this expression is undefined
When used with function calls , If the given function does not exist , Then return undefined.
const fa = { name: 'lming', son: { name: 'lqq' } }; const duc = fa.duc?.name;
console.log(duc); // output undefined
<> use :
<>1. Get a deeper attribute of an object , Namely obj Medium first Under attribute second attribute .
To avoid error reporting , Judge before obtaining first Whether the attribute is null perhaps undefined, In get second attribute
use “ And ” operator
let num = obj.first && obj.first.second;
use ?. Optional chain operator
let num = obj.first?.second; <> Optional chains and function calls
When calling a method that may not exist , If the called method does not exist , Use optional chains to make expressions return automatically undefined Instead of throwing an exception
let result = someInterface.customMethod?.();
notes : If a property name exists and is not a function , use ?. Will still produce a TypeError abnormal (x.y is not a function).
<> Use null merge operators let customer = { name: "Carl", details: { age: 82 } }; let
customerCity= customer?.city ?? " Dark City "; console.log(customerCity); // “ Dark City ” <>
Short circuit calculation let a = null; let x = 0; let prop = a?.[x++]; console.log(x); // x
Will not be incremented , Still output 0
Technology