9
Author: Ashish Lahoti
Translator: Frontend Xiaozhi
Source: CSS-Tricket

There are dreams and dry goods. search 160ca9e9d835bd [Great Move to the World] Follow this brushing wit who is still doing dishes in the early morning.

This article GitHub https://github.com/qq449245884/xiaozhi has been included, the first-line interview complete test site, information and my series of articles.

The optional link ?. operator is used to access nested object properties using implicit null checks.

Overview

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

You can use nested ternary operators:

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

Or use if to check for null values:

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

Or a better way is to make it a one-line link && condition, like this:

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

What the above codes have in common is that the links can sometimes be very lengthy and become more difficult to format and read. This is the reason why the ?. ?. refactor the above code under 060ca9e9d83730:

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

Very nice.

grammar

?. grammar 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;
  }
}

Attributes

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 ?. access non-existent attributes:

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

method

Access to existing methods:

console.log(user.getFirstName()); 
// 前端小智

Access methods that don’t exist:

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

Use ?. access the non-existent method instead:

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

Array

Access the existing array:

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

Access methods that don’t exist:

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

Use ?. access a non-existent array instead:

console.log(user.dislikes?.[0]?.name); 
// "undefined"

?? Operator

We know that if the ?. operation symbol does not exist, it just returns undefined . In development, it may not return undefined but a default value. At this time, we can use the double-question ?? operator.

A bit abstract, let’s just take an example:

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

Need to return to the default value:

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

~End, I’m Shuwanzhi, and I’m going to SPA, see you next time!


code is deployed, the possible bugs cannot be known in real time. In order to solve these bugs afterwards, a lot of time was spent on log debugging. By the way, we recommend a useful BUG monitoring tool Fundebug .

Original: https://codingncoepts.com/javascript/optional-chaining-opeator-javascript/


王大冶
68.1k 声望105k 粉丝