In JavaScript, ?.
, !.
, and ??
are three different operators, each with its own purpose to enhance code simplicity and safety, especially when dealing with possible null or undefined values. Below is an explanation of each operator:
Optional Chaining Operator ?.
Usage: obj?.prop
or obj?.[expr]
Function: When accessing a deeply nested property, if the object obj
is null
or undefined
, the ?.
operator prevents an error from being thrown and instead returns undefined
, avoiding errors from trying to access non-existent properties.
Example:
|
|
Non-Null Assertion Operator !.
Usage: obj!.prop
Function: This operator tells the TypeScript compiler that you are sure the expression will never be null
or undefined
, thus avoiding warnings during type checking. Note that this only affects compile-time type checking and does not change runtime behavior, so if the expression is actually null
or undefined
, it will still result in a runtime error.
Example: (Assumes a TypeScript environment)
|
|
Nullish Coalescing Operator ??
Usage: value ?? fallback
功能: Returns the fallback
value if value is null
or undefined
; otherwise, it returns value
itself. This differs from the logical OR ||
operator, which returns fallback
if value
is any falsy value (such as 0, false, an empty string, etc.), whereas ??
only replaces value
when it is strictly null
or undefined
.
Example:
|
|
In summary, ?.
helps safely access object properties, !.
is used to tell the TypeScript compiler to ignore possible null
or undefined
checks (ensure safety when using it), and ??
provides an alternative value when the original is null
or undefined
.