Home >Web Front-end >JS Tutorial >Let's talk about the optional (?.) operator in JavaScript

Let's talk about the optional (?.) operator in JavaScript

青灯夜游
青灯夜游forward
2021-06-15 11:34:161815browse

This article will introduce you to the optional (?.) operator in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Let's talk about the optional (?.) operator in JavaScript

How to use null (null and undefined) check to access the nested properties of an object? Suppose we have to access the interface from the backend Access user details.

You can use the nested ternary operator:

const userName = response ? (response.data ? (response.data.user ? response.data.user.name : null) : null) : null;

or use if for null value checking:

let userName = null;
if(response && response.data && response.data.user){
  userName = response.data.user.name;
}

Or better yet The && conditions that make it a single line link, like this:

const userName = response && response.data && response.data.user && response.data.user.name;

What the above codes have in common is that links can sometimes be very verbose and become harder to format and read. This is why the ?. operator was proposed. Let’s change it to ?. and reconstruct the above code:

const userName = response?.data?.user?.name;

is very nice.

Syntax

##?. The syntax was introduced in ES2020 and its usage is as follows:

obj.val?.pro  // 如果`val`存在,则返回`obj.val.prop`,否则返回 `undefined`。

obj.func?.(args) // 如果 obj.func 存在,则返回 `obj.func?.(args)`,否则返回 `undefined`。

obj.arr?.[index] // 如果 obj.arr 存在,则返回 `obj.arr?.[index]`,否则返回 `undefined`。

Use?.Operator

Suppose we have a

user object:

const user = {
  name: "前端小智",
  age: 21,
  homeaddress: {
    country: "中国"
  },
  hobbies: [{name: "敲代码"}, {name: "洗碗"}],
  getFirstName: function(){
    return this.name;
  }
}

Properties

Access existing attributes:

console.log(user.homeaddress.country); 
// 中国

Access non-existent attributes:

console.log(user.officeaddress.country); 
// throws error "Uncaught TypeError: Cannot read property 'country' of undefined"

Use

?. instead. Access non-existent attributes:

console.log(user.officeaddress?.country); 
// undefined

Method

Access existing methods:

console.log(user.getFirstName());

Access non-existent methods:

console.log(user.getLastName()); 
// throws error "Uncaught TypeError: user.getLastName is not a function";

Use

?. instead to access non-existent methods Method:

console.log(user.getLastName?.()); 
// "undefined"

Array

Access an existing array:

console.log(user.hobbies[0].name); 
// "敲代码"

Access a non-existent method:

console.log(user.hobbies[3].name); 
// throws error "Uncaught TypeError: Cannot read property 'name' of undefined"

Use # instead ##?.

Access non-existent array: <pre class="brush:js;toolbar:false;">console.log(user.dislikes?.[0]?.name); // &quot;undefined&quot;</pre>

??<strong></strong> OperatorWe know

?.

Operation symbol If the object does not exist, it will just return undefined. During development, it may not return undefined but return a default value. In this case, we can use double Question?? Operator. is a bit abstract, let’s take a direct example:

const country = user.officeaddress?.country;
console.log(country);
// undefined

Need to return the default value:

const country = user.officeaddress?.country ?? "中国";
console.log(country);
// 中国

English original address: https://codingncoepts.com/javascript/ optional-chaining-opeator-javascript/

Author: Ashish Lahoti

For more programming-related knowledge, please visit:
Introduction to Programming

! !

The above is the detailed content of Let's talk about the optional (?.) operator in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete