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:
Originallypickup
, dropoff
If there is no data in the two fields, it should be returned{}
, and nowpickup
Field returnednull
And 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 Henry
Relevant 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)(null
perhapsundefined
)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 exist
When usingOptional chain operator
Will make the expressionShorter and more concise
。
There are two points to note:
- 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 undefinedTypeError
Will still be thrown.
If you want to allow someinterfacenull
perhapsundefined
, then you need to write like thissomeInterface?.customMethod?.()
- Optional chain
Cannot 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);
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
);
Heny
Relevant information released
Heny is currentlybabel
The person in charge of the project has previously sent an article introducing the current Babel dilemma.
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.