Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to use OR condition in a JavaScript IF statement?
To use OR condition in JavaScript IF statement, use the || operator (Logical OR operator). The condition becomes true if any of the operands is truthy.
Syntax
if (condition1 || condition2) {
// Code executes if either condition1 OR condition2 is true
}
Basic OR Example
<html>
<body>
<script>
var a = true;
var b = false;
document.write("(a || b) => ");
result = (a || b);
document.write(result);
</script>
</body>
</html>
(a || b) => true
Practical IF Statement with OR
<html>
<body>
<script>
var age = 25;
var hasLicense = true;
if (age >= 18 || hasLicense) {
document.write("Can drive a car");
} else {
document.write("Cannot drive");
}
</script>
</body>
</html>
Can drive a car
Multiple OR Conditions
<html>
<body>
<script>
var day = "Saturday";
if (day === "Saturday" || day === "Sunday" || day === "Holiday") {
document.write("It's a weekend or holiday!");
} else {
document.write("It's a weekday");
}
</script>
</body>
</html>
It's a weekend or holiday!
OR with Different Data Types
<html>
<body>
<script>
var name = "";
var email = "user@example.com";
if (name || email) {
document.write("User has some contact info");
} else {
document.write("No contact info available");
}
</script>
</body>
</html>
User has some contact info
Key Points
- The
||operator returns true if any operand is truthy - Falsy values:
false,0,"",null,undefined,NaN - All other values are truthy
- Evaluation stops at the first truthy value (short-circuit evaluation)
Conclusion
The || operator in IF statements allows checking multiple conditions where only one needs to be true. This is essential for flexible conditional logic in JavaScript applications.
Advertisements
