Original link: zz

Definition of the optional chain operator

The optional chain operator (? .). Allows you to read the value of a property located deep in the chain of connected objects without explicitly validating that each reference in the chain is valid.

? The. Operator functions like the. Chain operator, except that it does not cause errors when references are null ([nullish]) ([null] or [undefined]. When used with a function call, returns undefined if the given function does not exist.

Basic usage

🌰

let allName = {
    name: "zz".age: {
        name: "cat"}}console.log(allName.genter ? . age)// undefined
Copy the code

🌰 🌰


letnestedProp = obj.first? .second;Copy the code

This code is equivalent to

let temp = obj.first;
let nestedProp = ((temp === null || temp === undefined)?undefined : temp.second);
Copy the code

🌰 🌰 🌰

const zz = {
  a: 'foo'.b: {
    c: 'bar'}}console.log(zz.b? .c)/ / output bar
console.log(zz.d? .c)/ / output is undefined
console.log(zz.func? . ()// No error, output undefine
Copy the code

In addition to retrieving an object’s property, optional chains can also be used to retrieve an array’s index, arr? .[index], can also be used to determine functions func? .(args), which can also be used when trying to call a method that may not exist.

When calling a method on an object that may not exist (for version reasons or if the current user’s device does not support the function), using an optional chain allows the expression to return undefined if the function does not exist instead of throwing an exception

Application scenarios

I’m sure many people use this in their projects to avoid JS errors

let allName = {
    name: "zz".age: {
        name: "cat"}}if(allName && allName.age && allName.age.name === "cat") {}Copy the code

Now that we have the optional chain operator, let’s try it out

if(allName ? . age ? . name ==="cat") {}Copy the code

🌰🌰 we use the null value merge operator to set a default value. What is null value merge operator? You can read this article, null value merge operator.

let customer = {
  name: "Carl".details: { age: 82}};letcustomerCity = customer? .city ??"zz";
console.log(customerCity); / / "zz"
Copy the code

Null value merge operator in js (??)

define

The null-value merge operator?? Is a logical operator that returns the right-hand operand if the left-hand operand is null or undefined, otherwise returns the left-hand operand.

Basic usage

const foo = null ?? "string"
// string

const foo = "zz" ?? "string"
// zz

const foo = undefined ?? "string"
// string

Copy the code

We can conclude from the above three cases that if the left-hand operand is null or undefined, return the right-hand operand, otherwise return the left-hand operand

I doubt

Null-value merge operator (??) And the logical or operator (| |) have what different, may everyone is often used in the project the Boolean or operator symbols (| |), that we are to compare the difference between them

Js the logical or operator (| |)

Logical operators | |, logical or operator will be on the left operand is false value returns the right operand.

Basic usage

const foo = null || "string"
// string

const foo = undefined || "string"
// string

cosnt foo = 0 || "string"
// string

cosnt foo = 0 || "string"
// string

const foo = "" || "string"
// string
Copy the code

After we compare the will find that if you use the | | to set default values for certain variables, may encounter unexpected behavior. For example, a false value (for example, ” or 0).

The business scenario

  • We find this problem in development and back-end tuning. The back end returns null for some reason when it should return an array. We can avoid some of the problems by using the null value merge operator at this point.
  • Make some judgments in the business, as follows
if(value ?? ' '! = =' ')
Copy the code

[Cannot be shared with AND OR OR operators]

will??Directly with AND (&&) and the OR (||The combination of the) operators is undesirable. Throw in this case because the priority/order of operations between the null-value merge operator and other logical operators is undefinedSyntaxError 。

null || undefined ?? "foo"; / / throw SyntaxError
true || undefined ?? "foo"; / / throw SyntaxError
Copy the code

However, it is fine to use parentheses to explicitly indicate the precedence of the operation:

(null || undefined)??"foo"; / / return "foo"
Copy the code