Typescript logical operators
Created By: chatGPT
In TypeScript, logical operators are crucial for controlling the flow of your application. The main logical operators are AND (
&&
), OR (||
), and NOT (!
). These operators allow you to combine multiple boolean expressions to create complex conditions. Understanding how these operators work can help you in making decisions based on multiple criteria.const a = true;
const b = false;
// AND operator
if (a && b) {
console.log('Both are true');
} else {
console.log('At least one is false'); // This will be executed
}
// OR operator
if (a || b) {
console.log('At least one is true'); // This will be executed
}
// NOT operator
if (!b) {
console.log('b is false'); // This will be executed
}
When using the AND operator (
&&
), the result is true
only if both operands are true
. For the OR operator (||
), the result is true
if at least one operand is true
. The NOT operator (!
) negates the boolean value of its operand.const x = 5;
const y = 10;
// Example of AND and OR
if (x > 0 && y > 0) {
console.log('Both x and y are positive');
}
if (x < 0 || y < 0) {
console.log('At least one is negative');
} else {
console.log('Both are non-negative'); // This will be executed
}
You can also use logical operators in combination with comparison operators to evaluate more complex conditions. This combination is widely used in if statements, loops, and other conditional logic to ensure that your application behaves correctly based on various inputs.
const age = 18;
const hasPermit = true;
// Combining logical and comparison operators
if (age >= 18 && hasPermit) {
console.log('You can drive');
} else {
console.log('You cannot drive'); // This will be executed if hasPermit is false
}
It's important to remember the short-circuit evaluation in logical operators. For instance, in an AND operation, if the first operand evaluates to
false
, TypeScript will not evaluate the second operand because the entire expression cannot be true
. Similarly, in an OR operation, if the first operand is true
, the second operand will not be evaluated.function checkValue(val: number) {
return val > 0 && (val / val > 1); // The second condition is not evaluated if val is 0
}
console.log(checkValue(0)); // Outputs: false
console.log(checkValue(5)); // Outputs: true
In summary, understanding and using logical operators effectively can enhance the way you control the flow of logic in your TypeScript applications.
const isWeekend = true;
if (isWeekend) {
console.log('Enjoy your weekend!');
} else {
console.log('Back to work!');
}