Logical Operators

Introduction

Logical operators in JavaScript are used to combine multiple conditions and return a true or false result. They are essential for decision making in programming and help control how code behaves based on different conditions.

Core Purpose of Logical Operators

Logical operators allow developers to evaluate more than one condition at a time. They are commonly used in conditional statements such as if statements, loops, and comparisons to control the flow of a program.

Types of Logical Operators

AND Operator

The AND operator returns true only when both conditions are true. If any condition is false, the result will be false.

Example

let age = 20;
let hasID = true;

if (age >= 18 && hasID) {
console.log("Access granted");
}

OR Operator

The OR operator returns true if at least one condition is true. It returns false only when all conditions are false.

Example

let isStudent = true;
let hasDiscountCard = false;

if (isStudent || hasDiscountCard) {
console.log("Discount applied");
}

NOT Operator

The NOT operator reverses the result of a condition. If a condition is true, it becomes false, and if false, it becomes true.

Example

let isLoggedIn = false;

if (!isLoggedIn) {
console.log("Please log in");
}

How Logical Operators Work

Logical operators evaluate conditions from left to right. They are often used to create complex conditions and make programs smarter and more efficient.

Real Life Use Cases

Checking user login and authentication
Validating form inputs
Controlling access to features
Filtering data based on conditions

Advantages

Makes decision making easier
Reduces complex nested conditions
Improves code readability
Widely used in real world applications

Conclusion

Logical operators are a fundamental part of JavaScript. Understanding how AND OR and NOT work will help you write smarter conditions and improve your programming skills.

Home ยป JavaScript Fundamentals (Beginner Level) > Operators and Conditions > Logical Operators