Conditions
Logical operators !, &&, ||
"Not", "and", "or": flip a condition and combine several conditions into one.
Why it exists
Real rules almost never consist of one condition: "let them in if they have a ticket and aren't banned", "show an error if the field is empty or the email has no @". Logical operators build such rules out of simple comparisons. And in JavaScript || and && can return not just true/false but the values themselves — that's how default values work.
Where it's used
- Compound conditions:
isLoggedIn && hasSubscription. - Validation:
!email || !email.includes("@")— empty, or no at sign. - Default values:
name || "Guest". - Conditional rendering in React:
{isOpen && <Menu />}.
Syntax
!a
a && b
a || bExamples
!true; // → false
!undefined; // → true
const age = 20;
age >= 18 && age < 65; // → true
age < 0 || age > 150; // → falseconst hasTicket = true;
const isBanned = false;
hasTicket && !isBanned; // → trueconst nickname = "";
nickname || "Guest"; // → "Guest"
"Ann" || "Guest"; // → "Ann"|| returns the first truthy valueconst user = null;
user && user.name; // → null — user.name was never reachedconst count = 0;
count || 10; // → 10 — zero is falsy
count ?? 10; // → 0 — ?? only looks at null and undefined?? is a default that leaves zero aloneResults after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
!x flips: truthy becomes false, falsy becomes true. A double !!x turns any value into an honest true/false.
a && b is evaluated left to right: if a is falsy, it stops and returns a; otherwise it returns b. a || b is the reverse: if a is truthy, it returns a right away; otherwise b. This is called short-circuiting: the right side may not run at all. That's why user && user.name doesn't crash when user is null.
Falsy values: false, 0, "", null, undefined, NaN. Everything else is truthy.
&& runs before ||, the way multiplication comes before addition. When in doubt, add parentheses.
Traps
How it differs from…
- Comparison:
===,!==,<,> Comparisons produce separate
true/falsevalues; logical operators combine them into one condition.
When to pick something else
Don't build long chains of five &&s and ||s on one line — split the condition into well-named variables: const canBuy = inStock && balance >= price;. For defaults where 0 or "" are valid, use ?? instead of ||.