Logical operators combine or flip boolean conditions.
&&(AND): true when both sides are true||(OR): true when at least one side is true!(NOT): flips a boolean, so!trueisfalse
const age = 25;
const hasTicket = true;
console.log(age >= 18 && hasTicket); // → true
console.log(age < 18 || hasTicket); // → true
console.log(!hasTicket); // → false
They return a value, not only true or false
This is the part that surprises people. && and || return one of their operands, and they stop as soon as the result is known. That is called short-circuiting.
a || breturnsaifais truthy, otherwiseb.a && breturnsaifais falsy, otherwiseb.
console.log("Maya" || "Guest"); // → Maya
console.log("" || "Guest"); // → Guest
console.log("Maya" && "Hello"); // → Hello
console.log(0 && "never seen"); // → 0
Default values with ||
function greet(name) {
const who = name || "stranger";
return "Hello, " + who;
}
console.log(greet("Maya")); // → Hello, Maya
console.log(greet()); // → Hello, stranger
The problem with ||
|| treats every falsy value as “missing”, including 0, "" and false, which are often valid.
const volume = 0;
console.log(volume || 50); // → 50 (wrong: 0 was a real choice)
console.log(volume ?? 50); // → 0 (correct)
When 0 or an empty string is allowed, use ??, see Nullish Coalescing.
Guarding with &&
Short-circuiting is also used to run something only when a condition holds:
const user = { name: "Maya" };
user.name && console.log("Hello, " + user.name); // → Hello, Maya
For clarity in larger code, prefer an if statement. Conditions are covered in the Conditions chapter.
Combining and the NOT operator
You can mix operators with parentheses: (a || b) && c. And ! turns any value into its opposite boolean: !0 is true, !"text" is false.