The ?? operator of JS is a null value coalescing operator, used to obtain non-null values in two expressions. It evaluates expressions in order from left to right, first checking the non-null value of the expression on the left, returning it if it is not null, and returning the value of the expression on the right if it is null. The difference between the ?? operator and the || operator is that it checks for null values and always returns a value. It's useful for providing default values, simplifying conditional statements, and avoiding lengthy if-else statements dealing with null values.
The ?? operator in JS
What is the ?? operator?
?? is called the null value coalescing operator and is used to obtain non-null values in two expressions. The syntax is as follows:
<code class="javascript">x ?? y</code>
How to use the ?? operator? The
?? operator evaluates expressions in left-to-right order:
x
first. x
is a non-null value (not null
or undefined
), then the value of x
is returned instead of The right-hand side expression y
is evaluated. x
is NULL, the right-hand expression y
is evaluated and its value is returned. Example:
<code class="javascript">const name = "John" ?? "Unknown"; // "John" const age = 0 ?? "N/A"; // 0 const empty = null ?? "Empty"; // "Empty" const undef = undefined ?? "Undefined"; // "Undefined"</code>
?? The difference between operator and || operator:
?? operator is similar to the logical OR operator (||), with the following difference: The
When to use the ?? operator? The
?? operator can be used to:
null
or undefined
value. if-else
statements when handling null values. The above is the detailed content of What does ?? mean in js?. For more information, please follow other related articles on the PHP Chinese website!