Home > Web Front-end > JS Tutorial > body text

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

青灯夜游
Release: 2021-06-16 09:43:03
forward
1787 people have browsed it

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;
Copy after login

or use if for null value checking:

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

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;
Copy after login

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;
Copy after login

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`。
Copy after login

Use?.Operator

Suppose we have a

user object:

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

Properties

Access existing attributes:

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

Access non-existent attributes:

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

Use

?. instead. Access non-existent attributes:

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

Method

Access existing methods:

console.log(user.getFirstName());
Copy after login

Access non-existent methods:

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

Use

?. instead to access non-existent methods Method:

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

Array

Access an existing array:

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

Access a non-existent method:

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

Use # instead ##?.

Access non-existent array: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false;">console.log(user.dislikes?.[0]?.name); // &quot;undefined&quot;</pre><div class="contentsignin">Copy after login</div></div>

??<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
Copy after login

Need to return the default value:

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

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template