Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”
This scenario is often encountered during development. A nested object called obj that needs to access properties deep in the object, such as obj.a.b.c, will raise TypeError when reading properties at the next level if one of the properties in the middle is not present.
To avoid this error, we have to add a check at each level to ensure that the value is neither null nor undefined
const obj = {}
// before ES2020 - no checks
obj.a.b // TypeError: Cannot read property 'b' of undefined
// before ES2020 - incremental nested checks
obj.a && obj.a.b // undefined
Copy the code
This method of incremental nested checking can be particularly verbose at deep levels, making it difficult to write or read
let d = obj.a && obj.a.b && obj.a.b.c && obj.a.b.c.d
Copy the code
Optional chain operator
A new feature is coming in ES2020: Optional chain operators? Use the optional chain operator to access obJ.a. b without explicitly verifying the state of OBj.A and then short-circuiting the final result
Basic usage
We rewrite the above code with the optional chain operator:
const obj = {}
// Optional Chainingobj.a? .b? .c? .d// undefined
Copy the code
The optional chain operator, which provides a way to simplify access to the value of the connected object, can safely access the object’s internal properties regardless of whether it exists or not.
The principle of
So how is the underlying implementation of optional operators? We can use Babel REPL to view the converted JS code
Before conversion:
After the transformation:
Simplify the above code to make it more readable:
You can see that using? The. Operator, js implicitly checks to make sure obj.a is neither null nor undefined before attempting to access obj.a.b. If null or undefined, the expression will short-circuit and return undefined.
Other uses:
Accessing an array:
For subscript access to arrays, you can use the optional chain operator
letitem = arr? .40];
Copy the code
Short circuit calculation:
When using optional chains in an expression, the expression will not be evaluated if the left-hand operand is null or undefined, for example:
let potentiallyNullObj = null;
let x = 0;
letprop = potentiallyNullObj? .[x++];console.log(x); // x will not be incremented and will still print 0
Copy the code
Babel configuration
Most modern browsers support the optional chain operator? For security and backward compatibility, it is recommended to configure the transformation plug-in in your project
// In package.json, install dependencies
{
"devDependencies": {
"@babel/core": "^ 7.12.9", (7.0The following Babel packages need to be deleted)"@babel/plugin-proposal-optional-chaining": "^ 7.12.7"(Depend on Babel7.0Above)"babel-loader": "^ 8.2.2". }... }// Create a new file ".babelrc.js" (in the same directory as package.json)
{
"plugins": [
"@babel/plugin-proposal-optional-chaining"]}Copy the code