JavaScript : Logical Operators

Logical operators are used to combine and evaluate logical conditions or expressions. There are three logical operators in JavaScript:

  1. And Operator: & &
  2. Or Operator: ||
  3. Not Operator: !

AND (&&) Operator

The AND operator returns true if both conditions on either side of it are true; otherwise, it returns false. It can be represented as "condition1 && condition2".

let age = 25; let hasLicense = true; if (age >= 18 && hasLicense) { console.log("You are eligible to drive."); } else { console.log("You are not eligible to drive."); }

In the above example, the code checks if the age is 18 or above and if the person has a valid driver's license. If both conditions are true, it will display the message "You are eligible to drive."

OR (||) Operator

The OR operator returns true if at least one of the conditions on either side of it is true; otherwise, it returns false. It can be represented as "condition1 condition2".

let isStudent = false; let isEmployee = true; if (isStudent isEmployee) { console.log("You are either a student or an employee."); } else { console.log("You are neither a student nor an employee."); }

In the above example, the code checks if the person is either a student or an employee. If at least one of the conditions is true, it will display the message "You are either a student or an employee."

NOT (!) Operator

The NOT operator is used to negate a boolean value. It returns true if the value is false, and false if the value is true. It can be represented as "!condition".

let isLoggedIn = false; if (!isLoggedIn) { console.log("Please log in to access the content."); } else { console.log("Welcome! You can access the content."); }

In the above example, the code checks if the user is not logged in. If the value of isLoggedIn is false, it will display the message "Please log in to access the content."

Conclusion

Logical operators in JavaScript enable the combination and evaluation of multiple conditions, allowing for complex decision-making and control flow in code.