Optional chaining operator ?. and null assignment operator ??

The optional chain operator?. and the null assignment operator?? are new features introduced in ES2020. Their functions are:

Optional chain operator?. :- It is used to optionally read the deep properties of the object. If the middle property does not exist, it will return undefined without reporting an error.

For example:

let name = obj.name;        // 如果 obj 不存在,这里会报错
let name = obj?.name;       // 如果 obj 不存在,返回 undefined

- Can be used to read object properties, call methods, access array elements, etc.

For example:

let age = person?.['age'];
let func = obj?.someMethod?.();
let first = arr?.[0]; 

Null assignment operator?? :

- Used to provide a default value when the target value is empty (null or undefined).

For example:

let name = obj.name ?? 'default'; 
// 等同于:
let name = obj.name || 'default';
// 但是 ?? 有另一个功能:如果obj.name为假值(如0)时,不会取'default'

- The default value will be taken only when the target value is null or undefined, and the default value will not be taken if the value is false (such as 0 or '').

So ?? is stricter than ||.

For example:

let age = 0 ?? 18;   // age 为 0
let age = '' ?? 18;  // age 为 ''
let age = null ?? 18; // age 为 18

Summarize:

Optional chaining operator?. It is used to optionally read the deep properties of the object, and returns undefined if the intermediate properties do not exist.
The null assignment operator ?? is used to provide a default value when the target value is null (null/undefined).
The optional chaining operator is based on security considerations, and the null assignment operator is based on strictness considerations.
Both are new features of ES2020, making object property reading and default value processing more concise and efficient.

Guess you like

Origin blog.csdn.net/qwe0415/article/details/131432263