Is the page white? Look at the optional chain operator (?.)

Time:2021-12-25

Is the page white? Look at the optional chain operator (?.)

background

Today, QA asked again: this page was fine yesterday, but today it is blank. Is there a problem with your code? Let’s have a look.

Go up and find the reason:

Is the page white? Look at the optional chain operator (?.)

Originallypickup, dropoffIf there is no data in the two fields, it should be returned{}, and nowpickupField returnednullAnd when we took the value, we didn’t defend this place.

list: openApiOrderInfo.pickup.address_list,

The result is:The script reports an error and the page is unavailable.

It’s easy to solve, either give me aDefault value, or use?.Make a layer of defense.

After the change, try again, it’s OK, and the page returns to normal.

Let’s talk about this?.

Today’s main content:

  • What is an optional chain operator(?.)
  • How do I enable this feature
  • Optional chain operator(?.)How does it work
  • HenryRelevant information released
  • summary

Text language

Optional chain operator(?.), we are all familiar with it. Here is a brief review.

What is an optional chain operator(?.)

Optional chain operator(?.)Allows you to read the value of an attribute deep in the chain of connected objects without explicitly verifying that each reference in the chain is valid.

For example, consider an object obj that has a nested structure. If the optional chain is not used, when finding a deeply nested sub attribute, the references between them need to be verified, for example:

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

To avoid error reporting, visit obj first. Before second, ensure obj The value of first is neither null nor undefined.

If you only directly access obj first. Second instead of obj First, it is possible to throw an error.

With the optional chain operator (?.), before accessing obj.first.second, it is no longer necessary to explicitly verify the status of obj.first, and then use short-circuit calculation to obtain the final result:

let nestedProp = obj.first?.second;

This is equivalent to the following expression, but no temporary variable is actually created:

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

?.The function of the operator is similar to.Chained operator, the difference is:

Null in reference (nullish)(nullperhapsundefined)In case ofNo errors will be caused, the return value of the expression is:undefined

When used with a function call, returns if the given function does not existundefined

When trying to accessObject properties that may not existWhen usingOptional chain operatorWill make the expressionShorter and more concise

There are two points to note:

  1. If a property name exists and is not a function, use A typeerror exception (x.y is not a function) will still be generated
let result = someInterface.customMethod?.();

Exception if someinterface itself is null or undefinedTypeErrorWill still be thrown.

If you want to allow someinterfacenullperhapsundefined, then you need to write like thissomeInterface?.customMethod?.()

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

How do I enable this feature

// install
npm install --save-dev @babel/plugin-proposal-optional-chaining

// babel config
{
 "plugins": [
    "@ Babel / plugin proposed optional chaining" // optional chaining
    "@ Babel / plugin proposal nullish coalescing operator", // double question mark
  ]
}

Optional chain operator(?.)How does it work

const a = {
  b: 1
};

console.log(a?.b);

Will be converted to:

const a = {
  b: 1
};

console.log(a === null ? void 0 : a.b);

Is the page white? Look at the optional chain operator (?.)

If the level is deeper, temporary variables are created for recording:

const a = {
  b: {
    c: 1,
    d: 2,
  }
};

console.log(a?.b?.c)

Will be converted to:

var _a$b;

const a = {
  b: {
    c: 1,
    d: 2
  }
};
console.log(
  a === null || a === void 0
    ? void 0 
    : (_a$b = a.b) === null || _a$b === void 0
      ? void 0
      : _a$b.c
);

Is the page white? Look at the optional chain operator (?.)

HenyRelevant information released

Heny is currentlybabelThe person in charge of the project has previously sent an article introducing the current Babel dilemma.

Is the page white? Look at the optional chain operator (?.)

Tweet link above: https://twitter.com/left_pad/…

Those interested can go and have a look.

summary

?.It is very convenient to use, but if it is not used well, it will hide the problems that should have been exposed.

Therefore, when using, you must know what you are doing.

?.And a little brother namedNull merge operator (?), I won’t talk about it here. Go to MDN to see the documents.

Today is so much. I hope it will inspire you.

Recommended Today

Necessary for Architects: principle and application of MySQL master-slave synchronization

In daily work, MySQL database is essential storage, in which read-write separation is basically standard configuration. Behind this, MySQL needs to turn on master-slave synchronization to form a master-slave or master-slave multi-slave architecture. Mastering the principle of master-slave synchronization and knowing how to apply it in practice are the necessary skills of an architect. The […]