TypeScript logical operators are similar to what we have learned in JavaScript logical operators. These operators help in comparing boolean expressions and producing a single boolean value as result.
1. Logical Operators
| Operator | Description |
|---|---|
Logical AND operator – && |
If both operands (or expressions) are true, then result will be true, else false.
let firstVar = true; let secondVar = false; console.log( firstVar && secondVar ); //false console.log( firstVar && true ); //true console.log( firstVar && 10 ); //10 which is also 'true' console.log( firstVar && '10' ); //'10' which is also 'true'
|
Logical OR operator – || |
If any of the two operands (or expressions) are true, then result will be true, else false.
let firstVar = true; let secondVar = false; console.log( firstVar || secondVar ); //true console.log( firstVar || true ); //true console.log( firstVar || 10 ); //true console.log( firstVar || '10' ); //true |
Logical NOT operator – ! |
It is used to reverse the logical state of its operand. It converts true to false, and vice-versa.
let firstVar = 10; let secondVar = 20; console.log( !true ); //false console.log( !false ); //true console.log( !firstVar ); //false console.log( !null ); //true |
Happy Learning !!
Comments