We have already used conditional statements to run code only if certain conditions are met. For example:
if (1 + 2 === 3) {
console.log("math still works");
}
We can create more complex conditions by combining individual conditions. We can do this by using the AND operator and the OR operator.
In JavaScript, we use two ampersands (&&
) to create an AND condition. An AND condition returns true
only if both sides return true
.
Basic Example
Try running these lines of code in the practice editor to see how AND works:
console.log(true && true); // true
console.log(true && false); // false
console.log(false && true); // false
console.log(false && false); // false
AND requires all values that it is comparing to be true
.
Advanced Example
Now try running the individual lines below in the practice editor:
1 + 2 === 3 && 4 > 3 * 1 // true
5 < 6 && 7 > 8 // false
Order of Operations
JavaScript executes operators in this order:
- Math (multiplication, addition, etc.)
- Comparison (equal, greater than, etc.)
- AND / OR
Think of it this way. The math has to happen first so JavaScript can compare the final results with the comparison operators. Then the comparison operators have to happen so JavaScript knows whether they returned true
or false
. Then JavaScript can execute the AND operator to check if they were all true
.
Let's use the example above:
// original:
1 + 2 === 3 && 4 > 3 * 1
// after math operators:
3 === 3 && 4 > 3
// after comparison operators:
true && true
// after AND operator:
true
In the end, the entire expression resolves to a single true
value.
Convenience
The AND operator lets us combine multiple if
statements into a single if
statement:
// BEFORE
if (plantsAvailable > 0) {
if (accountBalance > plantCost) {
"you can buy the plant!";
}
}
// AFTER
if (plantsAvailable > 0 && accountBalance > plantCost) {
"you can buy the plant!";
}