Skip to main content

Logical Operators

Introduction

In programming, logical operators are used to determine the logic between variables or values. TypeScript, like any other programming language, supports logical operators that allow us to make decisions based on multiple conditions. They return a boolean result - either true or false.

This article will explore the three basic logical operators in TypeScript: AND (&&), OR (||), and NOT (!).

Logical AND (&&)

The logical AND (&&) operator returns true if both operands (values or variables) are true. If at least one operand is false, it will return false. Here is an example:

let a = true;
let b = false;

console.log(a && b); // Output: false

In this example, a is true and b is false. Since both values are not true, the logical AND (&&) operator returns false.

Logical OR (||)

The logical OR (||) operator returns true if at least one of the operands is true. If both operands are false, it will return false. Here is an example:

let a = true;
let b = false;

console.log(a || b); // Output: true

In this example, a is true and b is false. Since one of the values is true, the logical OR (||) operator returns true.

Logical NOT (!)

The logical NOT (!) operator inverts the boolean result of the operand. If the operand is true, it returns false. If the operand is false, it returns true. Here is an example:

let a = true;

console.log(!a); // Output: false

In this example, a is true. The logical NOT (!) operator inverts this value, returning false.

Conclusion

Logical operators in TypeScript are essential in controlling the flow of your program. They allow you to make decisions based on multiple conditions, thereby increasing the flexibility and complexity of your code. As a beginner, it's essential to understand how to use these operators correctly. Practice using them in different scenarios to firmly grasp their utility.

Remember, logical AND (&&) returns true if both operands are true, logical OR (||) returns true if at least one of the operands is true, and logical NOT (!) inverts the boolean result of the operand.