7.1 Boolean Algebra
In JavaScript, there's a special logical data type for checking if conditions and expressions are true. In JavaScript, it's called Boolean and is used to represent one of two values: true or false.
This data type is super handy in programming for controlling the flow with conditional statements like if, else, and for loops and other structures.
Logical operators are used for doing logical operations on boolean values.
Key logical operators:
- Logical AND (represented as
&&) - Logical OR (represented as
||) - Logical NOT (represented as
!)
Let's dive deeper into each one.
7.2 Logical AND (&&)
The Logical AND operator returns true if both operands are true. Otherwise, it returns false.
Syntax:
a && b
Example:
let a = true;
let b = false;
console.log(a && b); // false
Usage:
The && operator is often used in conditional statements to check multiple conditions at once.
let age = 25;
let hasLicense = true;
if (age >= 18 && hasLicense) {
console.log('You can drive.');
}
7.3 Logical OR (||)
The Logical OR operator returns true if at least one of the operands is true. If both operands are false, it returns false.
Syntax:
a || b
Example:
let a = true;
let b = false;
console.log(a || b); // true
Usage:
The || operator is used to check if at least one of several conditions is true.
let isWeekend = true;
let isHoliday = false;
if (isWeekend || isHoliday) {
console.log('Today is a day off.');
}
7.4 Logical NOT (!)
The Logical NOT operator returns true if the operand is false, and false if the operand is true. It inverts the boolean value.
Syntax:
!a
Example:
let a = true;
console.log(!a); // false
Usage:
The ! operator is often used to invert boolean values and check negative conditions.
let isRaining = false;
if (!isRaining) {
console.log('You can go for a walk.');
}
7.5 Comparison Operators
For logical operations, comparison operators that return boolean values are often used:
| Operator | Description | Example | Result |
|---|---|---|---|
| == | Equal | 5 == '5' | true |
| === | Strictly equal (no type conversion) | 5 === '5' | false |
| != | Not equal | 5 != '5' | false |
| !== | Strictly not equal (no type conversion) | 5 !== '5' | true |
| > | Greater than | 10 > 5 | true |
| < | Less than | 10 < 5 | false |
| >= | Greater than or equal to | 10 >= 10 | true |
| <= | Less than or equal to | 10 <= 5 | false |
Examples of using comparison operators
Operators == and ===
console.log(5 == '5'); // true (type conversion)
console.log(5 === '5'); // false (strict comparison)
Operators != and !==
console.log(5 != '5'); // false (type conversion)
console.log(5 !== '5'); // true (strict comparison)
Operators >, <, >=, <=
console.log(10 > 5); // true
console.log(10 < 5); // false
console.log(10 >= 10); // true
console.log(10 <= 5); // false
GO TO FULL VERSION