What is the OR Operator in JavaScript?
The OR operator in JavaScript is a logical operator represented by ||
. It is used to combine two or more conditions, returning the first truthy value or the last value if all are falsy. This operator is fundamental in control flow and conditional statements.
Syntax
The syntax for the OR operator is straightforward:
condition1 || condition2;
How It Works
The OR operator evaluates each condition from left to right. If it encounters a truthy value, it returns that value immediately without evaluating the remaining conditions. If all conditions are falsy, it returns the last condition.
Example 1:
let age = 18;
let isAdult = age >= 18 || age === 17;
console.log(isAdult); // Output: true
Explanation: Since age >= 18
is true, the OR operator returns true
without checking the second condition.
Common Use Cases
- Default Values:
Provide a default value if a variable is undefined or null.
javascript
let username = null;
let user = username || 'Guest';
console.log(user); // Output: 'Guest'
- Conditional Execution:
Execute code only if a condition is met.
javascript
function greet(message) {
message = message || 'Hello!';
console.log(message);
}
greet(); // Output: 'Hello!'
- Combining Conditions:
Check multiple conditions in anif
statement.
javascript
let score = 85;
if (score > 90 || score === 85) {
console.log('Excellent!');
}
// Output: 'Excellent!'
FAQs
Q1: What is short-circuit evaluation in the OR operator?
A1: It means the operator stops evaluating conditions as soon as it finds a truthy value, improving efficiency.
Q2: How does the OR operator handle non-boolean values?
A2: It converts values to booleans. Non-zero numbers, non-empty strings, and objects are truthy; others are falsy.
Q3: What’s the difference between ||
and ??
(nullish coalescing)?
A3: ||
checks for any falsy value, while ??
only checks for null
or undefined
.
Conclusion
The OR operator is a powerful tool in JavaScript for combining conditions and providing defaults. By understanding its behavior and use cases, you can write more efficient and readable code. Experiment with different scenarios to master its application!