After this lesson you can write small decisions in one line, guard against missing values, and set a default only when the value is really missing. These tools build directly on Truthy and falsy values, so skim that lesson first if you need to.
The ternary operator
An if/else is a statement: it does something but has no value of its own. When all you want is to pick between two values, the ternary operator is shorter. It is the only JavaScript operator with three parts:
condition ? valueIfTrue : valueIfFalse<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
const age = 20;
const label = age >= 18 ? "adult" : "minor";
log(label);
const items = 1;
log("You have " + items + (items === 1 ? " item" : " items"));
</script>The output is adult and then You have 1 item. Because the ternary produces a value, you can use it right inside a string, an argument or an assignment, which an if statement cannot do.
Keep ternaries to one level. Nesting them, a ? b : c ? d : e, is legal, but readers have to work out which : belongs to which ?. If you need three outcomes, use if and else if from if, else and else if.
&& and || return values, not just booleans
You first met && and || as ways to combine conditions. Their real behaviour is more interesting: they return one of the two values they were given, and they short-circuit, meaning they stop as soon as the answer is known.
a || breturnsaifais truthy; otherwise it returnsb.a && breturnsaifais falsy; otherwise it returnsb.
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
log("hello" || "default");
log("" || "default");
log(0 || 42);
log("hello" && "world");
log("" && "world");
log(null && "world");
</script>This prints hello, default, 42 and world, then two empty lines. The fifth result is the empty string, and the sixth is null, which our log helper joins as nothing (a real console.log(null) would print null). In every case, the value that decided the answer is the one you get back.
Using || for defaults
Before ?? existed, || was the standard way to supply a fallback:
const name = inputName || "Guest";If inputName is empty, undefined or null, you get "Guest". That is often what you want for text. But it has the flaw from the truthy and falsy lesson: it also replaces 0, false and "" even when they are valid.
Using && as a guard
&& is handy for "only do this if that exists":
const city = user && user.address && user.address.city;If user is null, the expression stops there and returns null instead of crashing with an error for reading a property of null. Modern JavaScript has a neater tool for this, optional chaining (user?.address?.city), which has its own lesson later in the course. You will also see isReady && doSomething() as a shorthand for if (isReady) doSomething(). It works, but an if statement is clearer for actions.
The nullish coalescing operator ??
?? supplies a default only when the left side is null or undefined. Every other value, including 0, false and "", is kept.
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
const settings = { volume: 0, title: "", theme: undefined };
log("volume with ||:", settings.volume || 50);
log("volume with ??:", settings.volume ?? 50);
log("theme with ??:", settings.theme ?? "light");
log("missing with ??:", settings.language ?? "en");
</script>The four lines are volume with ||: 50, volume with ??: 0, theme with ??: light and missing with ??: en. A user who set the volume to zero wants silence. || ignores that choice, ?? respects it.
A simple rule: if zero, false or an empty string could be a real answer, use ??. If you want to treat all "empty-looking" values as missing, use ||.
?? is supported by all current major browsers and by modern Node.js versions. A related operator, ??=, assigns only if the variable is null or undefined: options.retries ??= 3;.
Mixing operators safely
JavaScript refuses to let you combine ?? with && or || without parentheses, because the intent would be ambiguous. This is a syntax error: a || b ?? c. Write (a || b) ?? c or a || (b ?? c) and say what you mean.
Also remember that the ternary has low precedence. In "Total: " + qty > 1 ? "many" : "one" the + and > are evaluated first, which is not what you want. Put the ternary in parentheses whenever it sits inside a larger expression, as in the items example above.
Common mistakes
- Using
||for numeric defaults.const port = config.port || 3000turns a deliberate0into3000. Use??. - Nesting ternaries. One level is fine. Two or more are hard to read and easy to get wrong. Use
ifandelse if. - Using a ternary for side effects.
isAdmin ? showAdmin() : hideAdmin();runs, but anifstatement tells the reader you are performing actions, not choosing a value. - Forgetting the parentheses around a ternary inside text.
"You have " + n === 1 ? ...compares the whole string to 1. Wrap it:"You have " + (n === 1 ? "one" : "many"). - Expecting
&&and||to return true or false. They return an operand. If you need a real boolean, wrap the result inBoolean(...). - Mixing
??with||without parentheses. It is a syntax error, not a subtle bug, so the message is your friend.
Exercise
- Write
const message = isLoggedIn ? "Welcome back" : "Please sign in"and test it with both values ofisLoggedIn. - Create an object
{ name: "", score: 0, bio: null }. Logname || "Anonymous",score || 10,score ?? 10andbio ?? "No bio yet". Before you run it, write down what you expect each to print, then compare. - Write a function
plural(count, word)that returns for example"1 apple"or"3 apples"using a ternary. Does it work for zero? What should it print?
Next, we move from choosing to repeating: for loops.
Key points
- The ternary operator condition ? a : b picks one of two values and is an expression, so it can be used inside other code.
- and || return one of their operands, not necessarily true or false, and they stop as soon as the answer is known.
- value || fallback replaces any falsy value, while value ?? fallback replaces only null and undefined.
- Use ?? for defaults when 0, false or an empty string are legitimate values.
- Do not nest ternaries or mix ?? with && or || without parentheses; use if when the logic gets long.