Logical Operators
Logical operators combine or invert conditions: "the balance is above zero and the due date has passed", "the student is in grade 9 or grade 10", "not paid". JavaScript's logical operators also do something most languages' don't: they return one of the original values, not just true or false. That makes them the standard way to supply defaults and to read data that might be missing.
In One Minute
&&(AND) is true when both sides are true.||(OR) is true when at least one is.!(NOT) flips a boolean.- They short-circuit:
a && bdoesn't evaluatebifais falsy;a || bdoesn't evaluatebifais truthy. a || breturns the first truthy value;a ?? breturnsaunless it isnullorundefined. Use??for defaults, so0and""survive.obj?.propreads a property but givesundefinedinstead of throwing whenobjisnullorundefined.x ??= valueassigns only ifxisnullorundefined;||=and&&=work the same way for their operators.
AND, OR and NOT
| Operator | Name | True when |
|---|---|---|
a && b | AND | Both a and b are true |
a || b | OR | At least one is true |
!a | NOT | a is false |
const balance = 120;
const daysLate = 12;
const hasWaiver = false;
console.log(balance > 0 && daysLate > 10);
console.log(daysLate > 30 || hasWaiver);
console.log(!hasWaiver);
const chargeLateFee = balance > 0 && daysLate > 10 && !hasWaiver;
console.log("Charge late fee?", chargeLateFee);true
false
true
Charge late fee? trueShort-Circuit Evaluation
JavaScript evaluates logical operators from left to right and stops as soon as the answer is known. If the left side of && is falsy, the whole thing must be falsy, so the right side never runs. If the left side of || is truthy, the right side never runs.
function expensiveCheck() {
console.log("expensiveCheck ran");
return true;
}
console.log(false && expensiveCheck());
console.log(true || expensiveCheck());
console.log(true && expensiveCheck());false
true
expensiveCheck ran
trueExplanation: in the first two lines, the answer is known from the left side, so expensiveCheck is never called. Only in the third line does && need the right side.
They Return Values, Not Just Booleans
Here is the part that is special to JavaScript. && and || return one of their operands:
a || breturnsaifais truthy, otherwiseb.a && breturnsaifais falsy, otherwiseb.
A value is truthy if it counts as true in a condition and falsy if it counts as false. The falsy values are false, 0, -0, 0n, "", null, undefined and NaN; everything else is truthy. The next chapter's truthy and falsy lesson covers them in depth.
console.log("Navika" || "Guest");
console.log("" || "Guest");
console.log(0 || 50);
console.log("Navika" && "logged in");
console.log(null && "logged in");Navika
Guest
50
logged in
nullNullish Coalescing: ??
Using || for defaults has a problem: 0 and "" are falsy, so they are replaced even when they are real, valid values. A student with a $0 balance would be shown the default instead.
The nullish coalescing operator ?? fixes this. a ?? b returns b only when a is nullish, meaning null or undefined:
const balance = 0;
const nickname = "";
let discount;
console.log(balance || 100);
console.log(balance ?? 100);
console.log(nickname || "No nickname");
console.log(nickname ?? "No nickname");
console.log(discount ?? 0);100
0
No nickname
0Explanation: with ||, the real balance 0 was thrown away and replaced by 100, a bug. With ??, 0 is kept because it isn't null or undefined. The empty nickname printed as an empty line, which is correct: the value was "", not missing.
Optional Chaining: ?.
Reading a property of null or undefined throws a TypeError. Data from forms, files and servers is often incomplete, so code like student.address.city crashes when a student has no address.
Optional chaining ?. stops and returns undefined when the value on its left is null or undefined:
const navika = { name: "Navika", address: { city: "Dallas" } };
const advitha = { name: "Advitha" };
console.log(navika.address?.city);
console.log(advitha.address?.city);
console.log(advitha.address?.city ?? "City not given");
console.log(advitha.getSchedule?.());
console.log(advitha.fees?.[0]);Dallas
undefined
City not given
undefined
undefinedExplanation: ?. works for properties (?.city), method calls (?.(), which calls the function only if it exists) and bracket access (?.[0]). Combined with ??, it reads nested data and supplies a fallback in one line.
Logical Assignment: ||=, &&=, ??=
These combine a logical operator with assignment. Like the operators, they short-circuit: the assignment happens only when needed.
| Operator | Means | Assigns when x is |
|---|---|---|
x ??= v | x ?? (x = v) | null or undefined |
x ||= v | x || (x = v) | falsy |
x &&= v | x && (x = v) | truthy |
const settings = { currency: "USD", pageSize: 0 };
settings.currency ??= "EUR"; // already set: unchanged
settings.pageSize ??= 20; // 0 is not nullish: unchanged
settings.theme ??= "light"; // missing: assigned
console.log(settings);{ currency: 'USD', pageSize: 0, theme: 'light' }In Practice
The Fee Tracker builds a summary line from a record that may be missing fields, using all three modern operators:
function summary(record) {
const name = record.name ?? "Unknown student";
const city = record.contact?.city ?? "no city";
const balance = record.balance ?? 0;
const status = balance > 0 && !record.waived ? "owes" : "is clear,";
return `${name} (${city}) ${status} $${balance}`;
}
console.log(summary({ name: "Srihitha", contact: { city: "San Francisco" }, balance: 80 }));
console.log(summary({ name: "Advitha", balance: 0 }));
console.log(summary({}));Srihitha (San Francisco) owes $80
Advitha (no city) is clear, $0
Unknown student (no city) is clear, $0Common Mistakes
Using || for numeric defaults. quantity || 1 turns a real 0 into 1. Use ??.
Mixing ?? with || or && without parentheses. a || b ?? c is a SyntaxError. Add parentheses: (a || b) ?? c.
Expecting && to return a boolean. user && user.name returns the name (or the falsy user). If you need a real boolean, use Boolean(x) or !!x.
Using ?. on the left of an assignment. student?.grade = 10 is a SyntaxError. Optional chaining only reads.
Interview Corner
What is the difference between || and ???
a || b returns b when a is any falsy value (false, 0, -0, 0n, "", null, undefined, NaN). a ?? b returns b only when a is null or undefined. Use ?? for defaults so valid values like 0 and "" are kept.
What does optional chaining do?
a?.b evaluates to undefined instead of throwing when a is null or undefined, and short-circuits the rest of the chain. It also works as a?.[key] and a.method?.(). It can't be used as an assignment target.
What does short-circuit evaluation mean?
The right operand of &&, || and ?? is evaluated only if the left operand doesn't decide the result. That's why user && user.save() calls save only when user is truthy, and why x ||= compute() calls compute only when needed.
Practice
Challenge: Write pageSize(options) that returns options.pageSize if it is set (including 0), otherwise 25. It must also work when options itself is undefined.
Show solution
function pageSize(options) {
return options?.pageSize ?? 25;
}
console.log(pageSize({ pageSize: 10 }));
console.log(pageSize({ pageSize: 0 }));
console.log(pageSize({}));
console.log(pageSize(undefined));10
0
25
25Key Takeaways
| Need | Write |
|---|---|
| Default for missing values | value ?? fallback |
| Read a nested value safely | obj?.a?.b |
| Call a method if it exists | obj.method?.() |
| Set only if missing | obj.key ??= value |
| Real boolean from a value | Boolean(value) |
Was this tutorial helpful?