JavaScript includes several operators that look similar but do very different things. Four you'll often see are the ternary operator (? :
), optional chaining (?.
), nullish coalescing (??
), and logical OR (||
). Here’s a quick guide to each — what they do, how they differ, and when to use them.
1. Ternary Operator (? :
)
What it does:
The ternary operator is a one-line shorthand for an if...else
statement, letting you pick one of two values based on a condition.
Syntax:
condition ? valueIfTrue : valueIfFalse
Example:
const age = 20;
const message = age >= 18 ? "Adult" : "Minor"; // "Adult"
// Equivalent to:
// let message;
// if (age >= 18) {
// message = "Adult";
// } else {
// message = "Minor";
// }
2. Optional Chaining (?.
)
What it does:
Optional chaining lets you safely access nested properties, returning undefined
instead of throwing an error if a property doesn’t exist.
Syntax:
object?.property
object?.[key]
object?.method?.()
Example:
const user = { profile: { name: "Alex" } };
const city = user.profile?.address?.city; // undefined (no error thrown)
// Without optional chaining:
// const city = user.profile.address.city; // TypeError!
3. Nullish Coalescing Operator (??
)
What it does:
??
provides a default value only if the left side is null
or undefined
(not other falsy values like 0
or ""
).
Syntax:
value ?? defaultValue
Example:
const input = 0;
const result = input ?? 100; // 0
// `??` does NOT replace 0, only null/undefined!
4. Logical OR Operator (||
)
What it does:
||
returns the right side if the left side is falsy (0
, ""
, false
, null
, or undefined
).
Syntax:
value || defaultValue
Example:
const username = "" || "Guest"; // "Guest"
const count = 0 || 10; // 10
Caution:
Be careful—||
will replace 0
, ""
, or false
with the default! Use it only when you want any falsy value to result in a fallback.
Quick Summary Table
Operator | Purpose | Fallback Only If | Example | Result | ||||
---|---|---|---|---|---|---|---|---|
? : |
Conditional/pick value | — | a ? x : y |
x or y
|
||||
?. |
Safe nested access | property missing | obj?.prop |
value/undefined | ||||
` | ` | Fallback on any falsy value | Any falsy (0 , "" …) |
`x | y` |
x or y
|
||
?? |
Fallback on null/undefined | null/undefined only | x ?? y |
x or y
|
Rule of thumb:
- Use
?.
to safely access deep properties. - Use
??
to fall back only for “missing” (null
/undefined
) values. - Use
||
for any type of falsy fallback (but avoid if0
or empty string is meaningful!). - Use
? :
for concise, conditional choices.
Top comments (0)