Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities.

1. The link operator is optional

Optional Chaining

1.1 introduction

In business development, if you read an attribute inside an object, you often need to determine whether the object exists. For example, a field name that reads a name directly from the interface, deep in the object hierarchy such as res.data.info.name, is safe to write as follows.

const name = (res && res.data && res.data.info && res.data.info.name) || 'defaultName'
Copy the code

In the example above, the name attribute is at the fourth level of the object, so you need to check four times to see if each level has a value.

Such layers of judgment can be tedious, so ES2020 has introduced the “optional chain operator” to simplify the above writing. The rewritten syntax reads as follows.

constname = res? .data? .info?.name ||'defaultName'
Copy the code

1.2 Basic Usage

let myMap = new Map()
myMap.set('artist', { name: 'Alice'.age: 23 })
myMap.get('doctor')? .name// undefined
myMap.get('artist')? .name// 'Alice'
Copy the code

The value of an expression in an object

let obj = { food1: 'aaa'.food2: 'bbb' }
    prop = 'food'
    type = '2'
letnestedProp = obj? .[prop + type]// 'bbb'
Copy the code

A function call

const Fn = () = > {console.log('run')}
letresult = Fn? . ()// 'run'
Copy the code

Access to an array

const arr = [1.2]
letarrayItem = arr? .42] // undefined
Copy the code

Short circuit calculation

When using optional chains in an expression, the expression will not be evaluated if the left-hand operand is null or undefined, for example:

let left = null
let i = 0
letresult = left? .[i++]console.log(i) // I will not be incremented and will still print 0
Copy the code

The delete operator.

Similar to short-circuit calculation, when the left-hand operand is null or undefined, undefined is returned without delete.

deletea? .bCopy the code

2. Null value merge operator

Nullish Coalescing

2.1 introduction

When reading object properties, you sometimes need to specify default values for them. Common practice is to pass | | operators to implement.

const object = { test: 0 }
const text = object.test || 'Hello World~' // 'Hello World~'
Copy the code

Sometimes, in development, you just want to set the default value for null or undefined, that is, to keep the value 0, false, and “.

In this case, you can use the null value merge operator, a new feature of ES11. . The null-value merge operator is a logical operator that returns the right-hand operand when the left-hand operand is null or undefined

2.2 Basic Usage

const object = { test: 0.test2: null }
const text = object.test ?? 'Hello World~' / / 0
const text2 = object.test2 ?? 'Hello World~' // 'Hello World~'
Copy the code

Short circuit calculation

If the left-hand operand is null or undefined, the expression will not be evaluated. For example:

function foo() {
  console.log('calling foo')}console.log(false ?? foo()) // foo is not executed
console.log(undefined ?? foo()) // 'call foo'When used with the logical operator, you need to add () to distinguish itconst small = true, medium = false, huge = true;
small && medium ?? huge / / an error
small ?? medium || huge / / an errorPlus small && Medium?? huge// false
small ?? (medium || huge) // true
Copy the code

3. Promise.allSettled

3.1 introduction

This is a pity. All is a method of ES6 that is used to accept multiple Promise instances. When the states of all instances become fulfilled, an array of results will be returned. Reject returns promise. reject when one instance becomes reject, and the results of other requests will not be returned normally.

In some cases, we want the results of other requests to return normally even when an instance is rejected. In this case, ES2020 introduces the promise.allSettled () method.

3.2 Basic Usage

const promise1 = new Promise((resolve, reject) = > setTimeout(reject, 200.'reject'))
const promise2 = new Promise((resolve, reject) = > setTimeout(resolve, 300.'resolve'))
const promises = [promise1, promise2]
 
Promise.allSettled(promises).then((res) = > res.forEach((item) = > console.log('result', item)))
// result {status: "rejected", reason: "reject"}
// result {status: "fulfilled", value: "resolve"}
Copy the code

This method returns a new Promise instance, again passing in an array of primse instances, and the result is always a depressing state. Sometimes we don’t care about the outcome of an asynchronous operation execution, but only whether the operation is finished, so try using the promise.allSettled () method.

Praise support, hand left lingering fragrance, with rongyan, move your rich little hands yo, thank you big guy can leave your footprints.

Past wonderful recommendation

Front-end common encryption methods

Canvas Pit Climbing Road

Don’t know SEO optimization? An article helps you understand how to do SEO optimization

Canvas Pit Road

Wechat small program development guide and optimization practice

Talk about mobile adaptation

Front-end performance optimization for actual combat

Talk about annoying regular expressions

Obtain file BLOB stream address to achieve the download function

Vue virtual DOM confused? This article will get you through the virtual DOM once and for all

Git Git

Easy to understand Git introduction

Git implements automatic push

Interview Recommendations

Front ten thousand literal classics – the foundation

Front swastika area – advanced section

More exciting details: personal homepage