Use of js optional chaining operator

Use of js optional chaining operator

Preface

The optional chaining operator (?.) allows reading the value of a property located at the end of a chain without having to explicitly verify that each reference in the chain is valid. The difference is that if the reference is null or undefined, no error will occur and the short-circuit return value of the expression is undefined. When used with a function call, if the given function does not exist, undefined is returned.

The optional chaining operator makes expression roots shorter and more concise when trying to access object properties that may not exist. The optional chaining operator is also helpful when exploring the contents of an object, when you are unsure which properties must be present.

Optional Chaining Operator (?.)

grammar

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

describe

The optional chaining operator provides a way to simplify accessing the value of a connected object when the reference or function passed through the connected object may be undefined or null.
For example, consider an object obj that has a nested structure. Without optional chaining, when looking up a deeply nested sub-property, you need to verify the references between them, for example:

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

To avoid errors, before accessing obj.first.second, make sure that the value of obj.first is neither null nor undefined. If you simply access obj.first.second without verifying obj.first, an error may be thrown.
With the optional chaining operator (?.), we no longer need to explicitly check the state of obj.first before accessing obj.first.second and then use short-circuit evaluation to get the final result:

let nestedProp = obj.first?.second

By using the ?. operator instead of the . operator, JavaScript implicitly checks to make sure obj.first is neither null nor undefined before trying to access obj.first.second. If obj.first is null or undefined, the expression will short-circuit the calculation and return undefined directly.

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) 

use

We can use chainable operators with the babel compiler.

babel

yarn add @babel/plugin-proposal-optional-chaining --dev

Add .babelrc file

{
  "plugins": ["@babel/plugin-proposal-optional-chaining"]
}

Use in create-react-app

By default create-react-app does not allow modification of the babel configuration, here we need to install two additional modules to allow supplementation of the default configuration.

yarn add customize-cra react-app-rewired --dev

Add config-overrides.js file

const { useBabelRc, override } = require('customize-cra');
module.exports = override(useBabelRc());

Modify package.json

"scripts": {
  "start": "react-app-rewired start",
  "build": "react-app-rewired build",
  "test": "react-app-rewired test --env=jsdom"
}

eslint

After installing the babel compiler, you can use the ?. operator. But if you use eslint, you need to install babel-eslint to recognize this new syntax.

yarn add babel-eslint --dev

Add .eslintrc file

{
  "parser": "babel-eslint",
  "rules": {
    "strict": 0
  }
}

Use in vscode

The js validator of vscode currently does not recognize the ?. operator, so there will be an error warning:


To resolve the error warning:

Install the vscode extension ESLint, search and install ESLint in the extension store.

Modify vscode configuration (.vscode/settings.json):

{
  "eslint.alwaysShowStatus": true,
  "eslint.autoFixOnSave": true,
  "javascript.validate.enable": false, // Mainly this, turn off vscode's js validator "[javascript]": {
    "editor.formatOnSave": false,
  },
  "[javascriptreact]": {
  "editor.formatOnSave": false,
  },
}

Source: Optional Chaining Operator

This is the end of this article about the use of js optional chaining operator. For more relevant js optional chaining operator content, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Comprehensive analysis of the "&&" and "||" operators in JavaScript (summary)
  • Some magical effects of the plus sign (+) operator in JavaScript
  • JavaScript delete operator application example
  • JavaScript operator (~, &, |, ^, <<, >>) use cases
  • Parsing objects that cannot be deleted by the delete operator in JavaScript
  • js operator summary
  • Detailed explanation of JavaScript spread operator
  • JavaScript Boolean operator parsing && || !

<<:  Centos7.5 installs mysql5.7.24 binary package deployment

>>:  MYSQL8.0.13 free installation version configuration tutorial example detailed explanation

Recommend

How to use VUE and Canvas to implement a Thunder Fighter typing game

Today we are going to implement a Thunder Fighter...

Let's talk about the issue of passing parameters to React onClick

Background In a list like the one below, clicking...

Solution to ONLY_FULL_GROUP_BY error in Mysql5.7 and above

Recently, during the development process, the MyS...

Detailed explanation of MySQL joint query optimization mechanism

Table of contents MySQL federated query execution...

Detailed installation and configuration of hadoop2.7.2 under ubuntu15.10

There are many Hadoop installation tutorials on L...

How to quickly deploy Redis as a Docker container

Table of contents getting Started Data storage Co...

Discussion on more reasonable creation rules for MySQL string indexes

Preface Regarding the use of MySQL indexes, we ha...

Docker connects to the host Mysql operation

Today, the company project needs to configure doc...

HTML thead tag definition and usage detailed introduction

Copy code The code is as follows: <thead> &...

Vue custom directive details

Table of contents 1. Background 2. Local custom i...

CSS cleverly uses gradients to achieve advanced background light animation

accomplish This effect is difficult to replicate ...

Basic usage tutorial of MySQL slow query log

Slow query log related parameters MySQL slow quer...

MySQL transaction analysis

Transaction A transaction is a basic unit of busi...

6 solutions to IDEA's inability to connect to the MySQL database

This article mainly introduces 6 solutions to the...

How to install MySQL for beginners (proven effective)

1. Software Download MySQL download and installat...