Logical Operators

Updated · 7 min read
easyES2026javascriptoperatorsnullish-coalescingoptional-chaininginterview

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 && b doesn't evaluate b if a is falsy; a || b doesn't evaluate b if a is truthy.
  • a || b returns the first truthy value; a ?? b returns a unless it is null or undefined. Use ?? for defaults, so 0 and "" survive.
  • obj?.prop reads a property but gives undefined instead of throwing when obj is null or undefined.
  • x ??= value assigns only if x is null or undefined; ||= and &&= work the same way for their operators.

AND, OR and NOT

OperatorNameTrue when
a && bANDBoth a and b are true
a || bORAt least one is true
!aNOTa is false
logic.js▶ Try it
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);
Output
true
false
true
Charge late fee? true

Short-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.

short-circuit.js▶ Try it
function expensiveCheck() {
  console.log("expensiveCheck ran");
  return true;
}
 
console.log(false && expensiveCheck());
console.log(true || expensiveCheck());
console.log(true && expensiveCheck());
Output
false
true
expensiveCheck ran
true

Explanation: 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 || b returns a if a is truthy, otherwise b.
  • a && b returns a if a is falsy, otherwise b.

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.

values.js▶ Try it
console.log("Navika" || "Guest");
console.log("" || "Guest");
console.log(0 || 50);
console.log("Navika" && "logged in");
console.log(null && "logged in");
Output
Navika
Guest
50
logged in
null

Nullish 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:

nullish.js▶ Try it
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);
Output
100
0
No nickname
 
0

Explanation: 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:

optional.js▶ Try it
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]);
Output
Dallas
undefined
City not given
undefined
undefined

Explanation: ?. 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.

OperatorMeansAssigns when x is
x ??= vx ?? (x = v)null or undefined
x ||= vx || (x = v)falsy
x &&= vx && (x = v)truthy
logical-assignment.js▶ Try it
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);
Output
{ 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:

summary.js▶ Try it
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({}));
Output
Srihitha (San Francisco) owes $80
Advitha (no city) is clear, $0
Unknown student (no city) is clear, $0

Common 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
page-size.js▶ Try it
function pageSize(options) {
  return options?.pageSize ?? 25;
}
 
console.log(pageSize({ pageSize: 10 }));
console.log(pageSize({ pageSize: 0 }));
console.log(pageSize({}));
console.log(pageSize(undefined));
Output
10
0
25
25

Quick check: Logical operators

4 questions
1What is 0 ?? 5?
2What is 0 || 5?
3What does student.address?.city give when student has no address?
4In false && doWork(), when is doWork called?

Key Takeaways

NeedWrite
Default for missing valuesvalue ?? fallback
Read a nested value safelyobj?.a?.b
Call a method if it existsobj.method?.()
Set only if missingobj.key ??= value
Real boolean from a valueBoolean(value)

Was this tutorial helpful?

Lesson 10 of 139