JavaScript AND
JavaScript AND Operator is used to perform logical AND operation on two boolean operands.
AND Operator is usually used in creating complex conditions like combining two or more simple conditions.
AND Operator Symbol
The symbol used for AND Operator is &&
.
Syntax
The syntax to use AND Operator with operands a
and b
is
a && b
AND 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 and only if all the operands in that expression are true.
AND Truth Table
The following truth table provides the output of AND operator for different values of operands.
a | b | a && b |
---|---|---|
true | true | true |
true | false | false |
false | true | false |
false | false | false |
AND Operation returns true, only if both the operands are 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 AND 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 AND 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 greater than zero and even.';
} else {
document.getElementById('output').innerHTML += 'a is either not greater than zero or not even.';
}
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned about Logical AND Operator, its syntax, and usage with examples.