Home > Web Front-end > JS Tutorial > body text

What does ?? mean in js?

下次还敢
Release: 2024-05-01 05:06:41
Original
1019 people have browsed it

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.

What does ?? mean in js?

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>
Copy after login

How to use the ?? operator? The

?? operator evaluates expressions in left-to-right order:

  1. evaluates the left-hand expression x first.
  2. If 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.
  3. If 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>
Copy after login

?? The difference between operator and || operator:

?? operator is similar to the logical OR operator (||), with the following difference: The

  • ?? operator checks for null values, while the || operator checks for Boolean values. The
  • ?? operator always returns a value, while the || operator returns a value only if at least one expression is true.

When to use the ?? operator? The

?? operator can be used to:

  • Provide a default value, for example when processing a value that may be null or undefined value.
  • Simplify code in conditional statements, such as checking whether a variable is non-null.
  • Avoid lengthy 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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!