!What does an operator do?

Tells the compiler that the current data is not “empty”

    let some = string| undefine; .console.log(some! .length)Copy the code

Null means null undefine

?What does an operator do?

Compiler helps you determine “empty”

// Before if (foo && foo.bar && foo.bar.baz) { // ... } // After-ish if (foo? .bar? .baz) { // ... } // It can determine if arrays and functions are "empty", /** * Get the first element of the array if we have an array. * Otherwise return undefined. */ function tryGetFirstElement<T>(arr? : T[]) { return arr? . [0]; // equivalent to // return (arr === null || arr === undefined) ? // undefined : // arr[0]; } async function makeRequest(url: string, log? : (msg: string) => void) { log? .(`Request started at ${new Date().toISOString()}`); // roughly equivalent to // if (log ! = null) { // log(`Request started at ${new Date().toISOString()}`); // } const result = (await fetch(url)).json(); log? .(`Request finished at at ${new Date().toISOString()}`); return result; }Copy the code

“Empty” here means null undefine associated links

??What does a sign do?

If the value is empty, it is used.

let x = foo ?? bar();
// equivalent to
letx = (foo ! = =null&& foo ! = =undefined)? foo : bar();Copy the code

It and | | difference

  • ??The definition of “empty” isnull undefine
  • ||The definition of “empty” isnull undefine 0 NaN ""