Logical operators help you make decisions by combining or changing true/false values.
Logical operators in Javascript
condition1 && condition2 // AND condition1 || condition2 // OR !condition // NOT
AND (&&) returns true only if both conditions are true.
OR (||) returns true if at least one condition is true.
NOT (!) flips true to false and false to true.
const a = true && false; // false
const b = true || false; // true
const c = !true; // false
const d = !(false || true); // false
This program checks if a user is logged in and if they are an admin. It shows different messages based on these conditions.
const isLoggedIn = true; const isAdmin = false; if (isLoggedIn && isAdmin) { console.log('Show admin panel'); } else if (isLoggedIn && !isAdmin) { console.log('Show user dashboard'); } else { console.log('Please log in'); }
Logical operators work with values that are true or false, but JavaScript also treats other values as true or false (called truthy and falsy).
Use parentheses to group conditions clearly and avoid confusion.
Short-circuiting: AND stops checking if the first is false; OR stops if the first is true.
Logical operators combine or change true/false values to help make decisions.
AND (&&) needs both true, OR (||) needs one true, NOT (!) flips true/false.
They are useful for controlling what your program does based on multiple conditions.