Home >Web Front-end >JS Tutorial >How to use || in js
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.
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:
|| operator is usually used in the following scenarios:
<code class="js">const name = username || "Guest";</code>
<code class="js">const message = prompt || "No message entered";</code>
<code class="js">if (condition || alert("Error")) { // 执行代码 }</code>
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>
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!