The usage and meaning of [optional chain (.?)], [null value coalescing operator (??)], [null value assignment operator (??=)] of js

optional chaining (.?)

In js, undefined and null are two special data types, and the dot operator cannot be used to access attributes. The following code will report an error.

let a;
let b = a.name;

insert image description here

To avoid this error, you can use optional chaining.?

let a;
let b = a?.name;
b = a?.name?.age?.haha?.就是不报错

You can go on infinitely in the future, no matter how many attributes there are, as long as there is an attribute that can be accessed at the end, and the final result is accessed, it will be assigned to b, otherwise, undefined will be assigned to b.

Null coalescing operator (??)

When a is not equal to undefined or null, assign the value of a to b, otherwise assign the value of c to b.

let b;
let a = 0;
let c = {
    
     name:'zzzz' }
b = a ?? c;

Null assignment operator (??=)

When the value on the left side of ??= is null or undefined, the value of the variable on the right will be assigned to the variable on the left. All other values ​​will not be assigned. Also in some scenarios, a lot of code can be omitted.

let b = '你好';
let a = 0
let c = null;
let d =123
b ??= a;  // b = “你好”
c ??= d  // c = '123'

Guess you like

Origin blog.csdn.net/u013299635/article/details/125716398