JavaScript Logical Operators
Understanding AND, OR, and NOT operators for complex conditions
🧠What are Logical Operators?
Logical operators are used to combine or modify boolean values. They help you create complex conditions by combining multiple comparisons.
// Basic logical operator example
let age = 25;
let hasLicense = true;
let canDrive = age >= 18 && hasLicense;
console.log(canDrive); // true
Output:
true
Logical Operators
AND Operator
Both conditions must be true
true && true // true
OR Operator
At least one condition must be true
true || false // true
NOT Operator
Reverses the boolean value
!true // false
Nullish Coalescing
Returns right side if left is null/undefined
null ?? "default" // "default"
🔹 AND Operator (&&)
The AND operator returns true only when both conditions are true:
let isWeekend = true;
let isRaining = false;
console.log(isWeekend && !isRaining); // true (weekend AND not raining)
console.log(isWeekend && isRaining); // false (weekend but raining)
// Practical example
let age = 20;
let hasID = true;
let canEnterClub = age >= 18 && hasID;
console.log("Can enter club:", canEnterClub);
Output:
true
false
Can enter club: true
🔹 OR Operator (||)
The OR operator returns true when at least one condition is true:
let isMember = false;
let hasDiscount = true;
console.log(isMember || hasDiscount); // true (has discount)
// Default values with OR
let username = "";
let displayName = username || "Guest";
console.log("Welcome,", displayName);
// Multiple conditions
let isHoliday = false;
let isSick = true;
let isVacation = false;
let stayHome = isHoliday || isSick || isVacation;
console.log("Stay home:", stayHome);
Output:
true
Welcome, Guest
Stay home: true
🔹 NOT Operator (!)
The NOT operator flips the boolean value:
let isLoggedIn = false;
let needsLogin = !isLoggedIn;
console.log("Needs login:", needsLogin);
// Double NOT for boolean conversion
let value = "hello";
let isBoolean = !!value; // converts to boolean
console.log("Is truthy:", isBoolean);
// Practical example
let isOffline = false;
let canSync = !isOffline;
console.log("Can sync data:", canSync);
Output:
Needs login: true
Is truthy: true
Can sync data: true
🔹 Complex Logical Expressions
Combining multiple logical operators:
// User access control
let age = 25;
let isEmployee = true;
let isManager = false;
let hasPermission = true;
// Complex condition
let canAccessSystem = (age >= 18 && isEmployee) ||
(isManager && hasPermission);
console.log("System access:", canAccessSystem);
// Parentheses for clarity
let canEditContent = isEmployee && (isManager || hasPermission);
console.log("Can edit:", canEditContent);
Output:
System access: true
Can edit: true