JavaScript OR
JavaScript OR Operator is used to perform logical OR operation on two boolean operands.
OR Operator is usually used in creating complex conditions like combining two or more simple conditions.
OR Operator Symbol
The symbol used for OR Operator is ||
.
Syntax
The syntax to use OR Operator with operands a
and b
is
a || b
OR Operator supports chaining. For example, the syntax to write a condition with four boolean values is
a || b || c || d
The above expressions returns true if any of the operands is true.
OR Truth Table
The following truth table provides the output of OR operator for different values of operands.
a | b | a || b |
---|---|---|
true | true | true |
true | false | true |
false | true | true |
false | false | false |
OR Operation returns true, if any of the operands is true, else, it returns false.
Examples
In the following example, we take two Boolean variables with different combinations of true and false, and find their logical OR output.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var a = true;
var b = true;
var result = a || b;
document.getElementById('output').innerHTML += '\n' + a + ' || ' + b + ' is ' + result;
a = true;
b = false;
result = a || b;
document.getElementById('output').innerHTML += '\n' + a + ' || ' + b + ' is ' + result;
a = false;
b = true;
result = a || b;
document.getElementById('output').innerHTML += '\n' + a + ' || ' + b + ' is ' + result;
a = false;
b = false;
result = a || b;
document.getElementById('output').innerHTML += '\n' + a + ' || ' + b + ' is ' + result;
</script>
</body>
</html>
In the following example, we use logical OR Operator in If Statement’s Condition to combine two simple conditions to form a complex condition.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var a = 4;
if (a % 2 == 0 || a > 0) {
document.getElementById('output').innerHTML += 'a is either greater than zero or even.';
} else {
document.getElementById('output').innerHTML += 'a is neither greater than zero nor even.';
}
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned about Logical OR Operator, its syntax, and usage with examples.