Home  >  Article  >  Web Front-end  >  How to use || in js

How to use || in js

下次还敢
下次还敢Original
2024-05-01 04:45:28586browse

The || operator (logical OR) in JavaScript is used to compare two expressions and return a true value: if the left operand is true, then the left operand is returned. If the left operand is false, the right operand is returned. Common scenarios include: setting default values, checking for null values, and implementing short-circuit evaluation.

How to use || in js

Usage of || operator in JavaScript

The || operator in JavaScript, also known as logical OR operator, is used Compares two expressions and returns a true or false value, following these rules:

  • Returns the left operand if it is true.
  • If the left operand is false, the right operand is returned.

Usage scenarios

|| operator is usually used in the following scenarios:

  • Default value: Convert a Value specified as the default value of another value, for example:
<code class="js">const name = username || "Guest";</code>
  • Null value check: Checks whether a value is null and returns a non-null value, e.g. :
<code class="js">const message = prompt || "No message entered";</code>
  • Short-circuit evaluation: Stop evaluation when the left operand is true, thereby improving performance, for example:
<code class="js">if (condition || alert("Error")) {
  // 执行代码
}</code>

Example

The following are some examples of || operator usage:

<code class="js">// 返回第一个真值
console.log(true || false); // true

// 返回非空字符串
console.log("Hello" || null); // "Hello"

// 默认值
console.log(undefined || "Default"); // "Default"

// 短路求值
if (false || alert("Error")) {
  console.log("Code will not execute");
}</code>

Note

It should be noted that the || operator is the same as the && operator (logical AND) Instead, it returns the first true value, while the && operator returns the last true value. Additionally, the || operator can be used with any data type, but its use with pure numbers is not recommended as it may lead to unexpected results.

The above is the detailed content of How to use || in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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