Conditionals & Operators (??, ?.)
Published by Brayan K
Every interesting program makes decisions: show this if logged in, charge that if the cart isn't empty, fall back to a default when data is missing. Modern JavaScript gives you elegant tools for all of it — the ternary, nullish coalescing ??, and optional chaining ?..
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Choose whether decisions are independent or exclusive
An if statement runs its body when its condition is truthy. Separate if statements make separate decisions: more than one body can run. An if / else if / else chain selects at most one body, testing conditions from the top until one succeeds.
const score = 82;
if (score >= 50) {
console.log("passed");
}
if (score >= 80) {
console.log("distinction");
}
// ✅ Expected output:
// passed
// distinctionconst score = 82;
if (score >= 80) {
console.log("distinction");
} else if (score >= 50) {
console.log("passed");
} else {
console.log("retry");
}
// ✅ Expected output:
// distinctionReversing those thresholds would make the broader passing branch catch a distinction score before the later branch could see it. Read an exclusive chain as a priority list, and test the boundary values as well as a comfortable value in the middle.
function classify(score) {
if (score >= 80) {
return "distinction";
} else if (score >= 50) {
return "passed";
} else {
return "retry";
}
}
console.log(classify(49));
console.log(classify(50));
console.log(classify(79));
console.log(classify(80));
// ✅ Expected output:
// retry
// passed
// passed
// distinctionMake the intended body visible with braces
Without braces, if controls only the next statement. Indentation helps a person read, but it does not group JavaScript statements. A stray semicolon after the condition is also a complete empty statement, leaving the following block outside the decision.
const hasTicket = false;
if (hasTicket)
console.log("ticket accepted");
console.log("gate opened");
// ✅ Expected output:
// gate openedconst hasTicket = false;
if (hasTicket) {
console.log("ticket accepted");
console.log("gate opened");
} else {
console.log("ticket required");
}
// ✅ Expected output:
// ticket requiredUse braces for the whole intended body, including a single statement that may grow later. When an action runs unexpectedly, check the braces and any semicolon immediately after the condition before changing the condition itself.
Compare a value without assigning a new one
The assignment operator = stores a value and produces that assigned value. The strict comparison === asks whether two values match without converting their types. A mistaken assignment inside a condition can silently change the state being tested.
let approved = false;
if (approved = true) {
console.log("allowed");
}
console.log(approved);
// ✅ Expected output:
// allowed
// trueconst approved = false;
if (approved === true) {
console.log("allowed");
} else {
console.log("waiting");
}
console.log(approved);
// ✅ Expected output:
// waiting
// falseWith a const binding, the same accidental assignment fails instead of silently replacing the value. The error comes from assignment, not from using a boolean in a condition.
const approved = false;
if (approved = true) {
console.log("allowed");
}
// ✅ Expected error:
// TypeError: Assignment to constant variable.Prefer strict equality for comparisons here. Type Coercion (== vs ===) owns conversion during loose equality and the difference between truthiness and equality.
Express both ends of a range
Write a separate comparison for each boundary and combine them with &&. A chained expression such as 0 < value < 10 does not express a mathematical range: the first comparison produces a boolean that the second comparison then uses.
const value = 20;
console.log(0 < value < 10);
console.log(value > 0 && value < 10);
console.log(value <= 0 || value >= 10);
// ✅ Expected output:
// true
// false
// trueThe middle expression requires both comparisons to succeed. The final expression accepts either outside boundary. Choose inclusive operators deliberately: a score of zero is different from a score greater than zero. Parentheses make combined rules easier to audit.
const isMember = true;
const hasVoucher = false;
const isOpen = false;
console.log(isMember || hasVoucher && isOpen);
console.log((isMember || hasVoucher) && isOpen);
// ✅ Expected output:
// true
// falseLogical AND binds more tightly than logical OR. In the first expression, an existing member bypasses the open check. The second expression requires the venue to be open for either kind of visitor. Parentheses document which requirement applies to the whole alternative.
Short-circuiting chooses a value and skips work
Logical operators can return an operand rather than a boolean. && stops at a falsy operand; || stops at a truthy one. If no earlier operand stops evaluation, the last operand is returned. The skipped expression is not evaluated, including any function call it contains.
function inspect() {
console.log("inspected");
return "ready";
}
console.log(false && inspect());
console.log("cached" || inspect());
console.log(true && inspect());
// ✅ Expected output:
// false
// cached
// inspected
// readyA nonempty string is truthy even when its text is "false". Use a deliberate boolean comparison when that text represents a setting. The full conversion rules belong to Type Coercion (== vs ===).
function fee() {
console.log("calculating fee");
return 5;
}
const deliveryMode = "collect";
const deliveryFee = deliveryMode === "collect" ? 0 : fee();
console.log(deliveryFee);
// ✅ Expected output:
// 0The conditional operator has a condition, a value for the truthy case and a value for the falsy case. Use it when choosing a small value is clearer than assigning in two branches. For several actions or several levels of decisions, an if chain is usually easier to trace.
Nullish coalescing can preserve valid zero or empty-string values when supplying a default, and optional chaining can stop a property read at a nullish value. Optional Chaining & Nullish Coalescing owns those operators and the limits of their guards.
Stop a switch case when its work is finished
A switch selects a case using strict comparison with its expression. After entering a matching case, execution continues through later statements unless a break, return or other control transfer stops it. Case labels do not automatically end the previous case.
const mode = "collect";
switch (mode) {
case "collect":
console.log("collect at desk");
case "deliver":
console.log("send by courier");
break;
default:
console.log("choose a mode");
}
// ✅ Expected output:
// collect at desk
// send by courierconst mode = "collect";
switch (mode) {
case "collect":
console.log("collect at desk");
break;
case "deliver":
console.log("send by courier");
break;
default:
console.log("choose a mode");
}
switch ("2") {
case 2:
console.log("numeric case");
break;
default:
console.log("no numeric match");
}
// ✅ Expected output:
// collect at desk
// no numeric matchAdjacent empty case labels can intentionally share one body. When fall-through is intentional, make that visible in the code; when it is accidental, a nearby break is often the missing boundary. Use an if chain for ranges rather than pretending a case label is a range test.
Complete a dispatch decision
A dispatch can proceed only when the item is in stock and the delivery address is present. Fill the two blanks to combine the booleans and choose the label. The literal hints let you check the syntax before trying other combinations.
const inStock = true;
const hasAddress = false;
const canDispatch = ___; // 👉 replace ___ with inStock && hasAddress
const label = ___; // 👉 replace ___ with canDispatch ? "dispatch" : "hold"
console.log(canDispatch);
console.log(label);
// ✅ Expected output:
// false
// holdClassify a booking with an explicit priority
Write a function bookingStatus that accepts seats and paid. Return "invalid" when seats is not an integer or is less than one; otherwise return "payment due" when paid is false; otherwise return "confirmed". Use the fixed calls in the solution to exercise all three outcomes and the zero-seat boundary. The contract assumes seats is a number and paid is a boolean.
function bookingStatus(seats, paid) {
if (!Number.isInteger(seats) || seats < 1) {
return "invalid";
}
if (!paid) {
return "payment due";
}
return "confirmed";
}
console.log(bookingStatus(0, true));
console.log(bookingStatus(1.5, true));
console.log(bookingStatus(2, false));
console.log(bookingStatus(2, true));
// ✅ Expected output:
// invalid
// invalid
// payment due
// confirmedEach early return ends the function, so later checks only handle inputs that passed the earlier guard. If the inputs come from a form, parsing and validating their types are a separate responsibility; a nonempty string is not a boolean permission.
References: MDN explains if...else, logical AND, and switch.
Practice quiz
What does this complete program print? const score = 90; if (score >= 50) console.log("pass"); else if (score >= 80) console.log("distinction");
- pass
- distinction
- pass distinction
- No output
Answer: pass. An exclusive chain stops at its first truthy condition; the broader threshold catches this score first.
What does this complete program print? const enabled = false; if (enabled) console.log("first"); console.log("second");
- No output
- second
- first second
- first
Answer: second. Without braces, only the immediately following statement belongs to if.
What does this complete program print? let allowed = false; if (allowed = true) console.log("yes"); console.log(allowed);
- false
- No output
- yes true
- yes false
Answer: yes true. Assignment stores true and evaluates to true, so the branch runs and the variable stays changed.
What does this complete program print? const value = 20; console.log(value > 0 && value < 10);
- true
- 20
- TypeError
- false
Answer: false. The upper-bound comparison is false, so the combined range check is false.
What does this complete program print? console.log("saved" || "default"); console.log(0 && "ready");
- saved 0
- true false
- default ready
- saved ready
Answer: saved 0. OR returns the first truthy operand and AND returns the first falsy operand; neither must return a boolean.
What does this complete program print? function side() { console.log("called"); return 8; } console.log(false ? side() : 3);
- called 8
- 3
- called 3
- 8
Answer: 3. The ternary evaluates only its selected branch, so side is not called.
What does this complete program print? switch (1) { case 1: console.log("A"); case 2: console.log("B"); break; default: console.log("C"); }
- A
- B
- A B
- A B C
Answer: A B. After entering case 1, execution falls through case 2 until break exits the switch.
What does this complete program print? switch ("1") { case 1: console.log("matched"); break; default: console.log("different"); }
- matched
- matched different
- TypeError
- different
Answer: different. A switch uses strict comparison; a string does not match a numeric case.
Continue this course
- Previous: Loops & Iteration
- Next: Type Coercion (== vs ===) — == vs ===, truthy/falsy values, and avoiding coercion bugs
- Quick reference: JavaScript cheat sheet