Use of optional chain operators

Posted by minidak03 on Mon, 01 Nov 2021 09:55:40 +0100

Official website definition:

         Optional chain operator(  ?. ) Allows you to read the value of an attribute located deep in the chain of connected objects without explicitly verifying that each reference in the chain is valid   The function of the operator is similar to  .  Chain operator, the difference is that the reference is empty( nullish ) (null   perhaps   undefined )Will not cause an error, and the return value of the expression is   Undefined. When used with a function call, returns if the given function does not exist   undefined.

Advantages: when trying to access object properties that may not exist, the optional chain operator will make the expression shorter and more concise. When exploring the content of an object, the optional chain operator is also helpful if you are not sure which properties must exist

My understanding is to simplify the ternary judgment. First, I implicitly judge whether the variables before? Exist(   Neither   null   Neither   Undefined.) if it is null or undefind   The expression will be evaluated and returned directly   undefined.

// Normal writing: to avoid error reporting, ensure that the value of obj.first is not null before accessing obj.first.second,
//Nor / / undefined. If you only directly access obj.first.second without verifying obj.first, you may throw
//Wrong.

let nestedProp = obj.first && obj.first.second;

//Optional chain operator
//By replacing the. Operator with the?. operator, JavaScript implicitly checks and returns the obj.first.second before attempting to access it
//Make sure obj.first is neither null nor undefined. If obj.first is null or undefined, the expression will
//Short circuit calculation directly returns undefined.


let nestedProp = obj.first?.second

Syntax:

obj?.prop
obj?.[expr]
arr?.[index]
func?.(args)

Optional chains and function calls

An optional chain can also be used when trying to call a method that may not exist. When calling a function, if the called method does not exist, using an optional chain can make the expression automatically return undefined instead of throwing an exception.

Note: if "before" is not a method name but an attribute name, an error will be reported for ".. ()"

let result = someInterface.customMethod?.();

  Handle optional callback functions or event handlers

For example, try...catch

//  How to write ES2019
function doSomething(onContent, onError) {
  try {
    // ... do something with the data
  }
  catch (err) {
    if (onError) { // Verify whether onError really exists
      onError(err.message);
    }
  }
}

// Function calls using optional chains
function doSomething(onContent, onError) {
  try {
   // ... do something with the data
  }
  catch (err) {
    onError?.(err.message); // If onError is undefined, there will be no exception
  }
}

Optional chains and expressions

         When using [] to access the properties of an object:

      let name = person?.['age'+'name']

Optional chains cannot be used for assignment

let object = {};
object?.property = 1; 
// Uncaught SyntaxError: Invalid left-hand side in assignment

Optional chain access array elements

let arrayItem = arr?.[42];

  Short circuit calculation

When an optional chain is used in an expression, if the left operand is   null   or   undefined, the expression will not be evaluated, for example:

let potentiallyNullObj = null;
let x = 0;
let prop = potentiallyNullObj?.[x++];

console.log(x); // x will not be incremented and 0 will still be output

Multiple nested structures can be read continuously using optional chains:

let customer = {
  name: "Carl",
  details: {
    age: 82,
    location: "Paradise Falls" // The address property of details is not defined
  }
};
let customerCity = customer.details?.address?.city;

// ... optional chains can also be used with function calls
let duration = vacations.trip?.getTime?.();

Null merge operator

         The null merge operator (?) is a logical operator when the operand on the left is   null   perhaps   undefined   Returns its right operand, otherwise returns the left operand.

const foo = null ?? 'default string';
console.log(foo);
// expected output: "default string"

const baz = 0 ?? 42;
console.log(baz);
// expected output: 0

const nullValue = null;
const emptyText = ""; // Empty string, a false value, Boolean("") === false
const someNumber = 42;

const valA = nullValue ?? "valA Default value for";
const valB = emptyText ?? "valB Default value for";
const valC = someNumber ?? 0;

console.log(valA); // "Default value for valA"
console.log(valB); // "" (although the empty string is false, it is not null or undefined)
console.log(valC); // 42

Difference from or operator:

// "||"

let count = 0;
let text = "";

let qty = count || 42;
let message = text || "hi!";
console.log(qty);     // 42 instead of 0
console.log(message); // "hi!" instead of ""
// "??" only when the left side of?? is null or undefind, the value on the right side of?? will be executed

let count = 0;
let text = "";

let qty = count ?? 42;
let message = text ?? "hi!";
console.log(qty);     // 0
console.log(message); // ""

Short circuit:  

function A() { console.log('function A Called'); return undefined; }
function B() { console.log('function B Called'); return false; }
function C() { console.log('function C Called'); return "foo"; }

console.log( A() ?? C() );
// Print "function A called", "function C called" and "foo" successively
// A() returns undefined, so the expressions on both sides of the operator are executed

console.log( B() ?? C() );
// Print "function B called" and "false" successively
// B() returned false (neither null nor undefined)
// So the right expression is not executed

*****   ?? No   Directly with   AND (& &) AND OR (|) operators are used in combination

null || undefined ?? "foo"; // Throw syntax error
true || undefined ?? "foo"; // Throw syntax error

Null merge operator pair   undefined   And   null   These two values, Optional chain operator (?.)   The same is true.

Topics: Javascript