How to Use Logical Operators in JavaScript: Syntax and Examples
In JavaScript, logical operators like
&& (AND), || (OR), and ! (NOT) combine or invert boolean values. Use && to check if both conditions are true, || to check if at least one is true, and ! to reverse a condition's truth value.Syntax
Logical operators in JavaScript work with boolean values (true or false) to combine or invert conditions.
- && (AND): Returns true if both conditions are true.
- || (OR): Returns true if at least one condition is true.
- ! (NOT): Reverses the truth value of a condition.
javascript
condition1 && condition2 condition1 || condition2 !condition
Example
This example shows how to use logical operators to check multiple conditions and invert a condition.
javascript
const isSunny = true; const isWarm = false; // AND: true only if both are true const goOutside = isSunny && isWarm; console.log('Go outside (AND):', goOutside); // false // OR: true if at least one is true const wearSunglasses = isSunny || isWarm; console.log('Wear sunglasses (OR):', wearSunglasses); // true // NOT: reverses the value const stayInside = !isSunny; console.log('Stay inside (NOT):', stayInside); // false
Output
Go outside (AND): false
Wear sunglasses (OR): true
Stay inside (NOT): false
Common Pitfalls
Logical operators expect boolean values, but JavaScript sometimes treats other values as true or false (called "truthy" or "falsy"). This can cause unexpected results.
Also, using = (assignment) instead of == or === (comparison) inside conditions is a common mistake.
javascript
let a = 0; // Wrong: assignment inside if condition // if (a = 1) { // console.log('This runs because a is assigned 1'); // } // Right: comparison inside if condition if (a === 1) { console.log('a is 1'); } else { console.log('a is not 1'); } // Truthy/falsy example if (a) { console.log('a is truthy'); } else { console.log('a is falsy'); }
Output
a is not 1
a is falsy
Quick Reference
| Operator | Meaning | Example | Result |
|---|---|---|---|
| && | AND - true if both true | true && false | false |
| || | OR - true if one true | true || false | true |
| ! | NOT - reverses value | !true | false |
Key Takeaways
Use && to check if both conditions are true.
Use || to check if at least one condition is true.
Use ! to reverse a condition's truth value.
Remember JavaScript treats some values as truthy or falsy, which can affect logic.
Avoid using = instead of == or === in conditions to prevent bugs.