Consolidate JS optional (?.) Operation symbol, the original function can also be written in optional way, and learned again!

Posted by jlommori on Wed, 02 Feb 2022 03:18:16 +0100

Author: Ashish Lahoti
Translator: front end Xiaozhi
Source: CSS tricket

There are dreams and dry goods. Wechat search [Daqian world] pays attention to this dish washing wisdom who is still washing dishes in the early morning.

This article GitHub https://github.com/qq449245884/xiaozhi It has been included. There are complete test sites, materials and my series of articles for the interview of front-line large factories.

Optional link Operator is used to access nested object properties using implicit null checking.

summary

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

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 the null value:

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

Or a better way is to make it a && condition for 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 lengthy and become more difficult to format and read. This is it. The reason why the operator is proposed, let's change it Refactor the above code:

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

nice.

grammar

?. Syntax is introduced in ES2020, and its usage is as follows:

obj.val?.pro  // If 'val' exists, return 'obj val.prop `, otherwise, 'undefined' will be returned.

obj.func?.(args) // If obj Func exists, return ` obj func?. (args) `, otherwise ` undefined 'will be returned.

obj.arr?.[index] // If obj If arr exists, return ` obj arr?. [index] `, otherwise, 'undefined' will be returned.

use?. Operator

Suppose we have a user object:

const user = {
  name: "Front end Xiaozhi",
  age: 21,
  homeaddress: {
    country: "China"
  },
  hobbies: [{name: "Knock code"}, {name: "Wash the dishes"}],
  getFirstName: function(){
    return this.name;
  }
}

attribute

Access existing properties:

console.log(user.homeaddress.country); 
// China

Access nonexistent properties:

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

Use Access nonexistent properties:

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

method

Access existing methods:

console.log(user.getFirstName()); 
// Front end Xiaozhi

Access method that does not exist:

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

Use Access method that does not exist:

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

array

Access existing arrays:

console.log(user.hobbies[0].name); 
// "Tap code"

Access method that does not exist:

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

Use Accessing non-existent arrays:

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

?? Operator

We know 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 double question?? Operator.

A little abstract, let's take an example directly:

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

You need to return the default value:

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

~After that, I'm Zhihua. SPA, get up and see you next time!

The bugs that may exist after the code is deployed cannot be known in real time. Afterwards, in order to solve these bugs, we spent a lot of time on log debugging. By the way, we recommend a useful BUG monitoring tool Fundebug.

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

Topics: Front-end Vue css