TypeScript Logical Operators
Logical operators are used in TypeScript to combine conditions or invert a condition's value. These operators are often used in decision-making and control flow.
Types of Logical Operators
- AND (
&&
) - OR (
||
) - NOT (
!
)
AND (&&
) Operator
The &&
operator (Logical AND) checks if both conditions are true. If they are, it returns true
. If either condition is false, it returns false
.
Syntax:
condition1 && condition2
Example:
let age = 25;
let hasDrivingLicense = true;
if (age > 18 && hasDrivingLicense) {
console.log("You can drive.");
} else {
console.log("You cannot drive.");
}
Output:
You can drive.
OR (||
) Operator
The ||
operator (Logical OR) checks if at least one of the conditions is true. If either condition is true, it returns true
. If both conditions are false, it returns false
.
Syntax:
condition1 || condition2
Example:
let isWeekend = true;
let isHoliday = false;
if (isWeekend || isHoliday) {
console.log("You can relax today.");
} else {
console.log("You need to work today.");
}
Output:
You can relax today.
NOT (!
) Operator
The !
operator (Logical NOT) inverts the value of a condition. If the condition is true
, it returns false
, and if the condition is false
, it returns true
.
Syntax:
!condition
Example:
let isRaining = false;
if (!isRaining) {
console.log("You can go outside without an umbrella.");
} else {
console.log("You need an umbrella.");
}
Output:
You can go outside without an umbrella.
Combining Logical Operators
You can combine multiple logical operators to create complex conditions.
Example:
let age = 20;
let hasID = true;
let isMember = false;
if ((age >= 18 && hasID) || isMember) {
console.log("You can enter the club.");
} else {
console.log("You cannot enter the club.");
}
Output:
You can enter the club.
Conclusion
Logical operators in TypeScript make it easy to work with multiple conditions. By understanding how &&
, ||
, and !
work, you can control the flow of your programs effectively.