Complete Guide to JavaScript Question Mark (?) Syntax: Master These 3 Key Uses
Master the question mark (?) in JavaScript! Learn the ternary operator, optional chaining, and nullish coalescing with practical examples to write safer, cleaner code.
Have you ever scratched your head while coding in JavaScript, wondering about the mysterious question mark (?) that seems to pop up everywhere? It can look like an if statement, appear in the middle of object properties, or even show up between operators.
These question marks are actually incredibly useful syntax tools that make JavaScript code more concise and elegant. In real-world programming, they’re perfect for reducing repetitive code and handling exceptions efficiently.
In this post, we’ll break down the three essential uses of the question mark (?) in JavaScript: the ternary operator, optional chaining, and nullish coalescing. We’ll explain why they’re important and provide clear examples so you can understand how to use them in practice. By the end, you’ll no longer fear the question mark and will know how to use it like a pro!
1. Ternary Operator: condition ? value1 : value2
The ternary operator is the simplest use of the question mark and allows you to condense an if...else statement into a single line. As its name suggests, it operates on three components: a condition, a value if the condition is true, and a value if the condition is false.
- Syntax:
condition ? expression_if_true : expression_if_false
Let’s compare it to an if...else statement to see how it works:
// Using an if...else statement
let isAdult;
const age = 20;
if (age > 18) {
isAdult = true;
} else {
isAdult = false;
}
console.log(isAdult); // true
// Using the ternary operator
const isAdultTernary = age > 18 ? true : false;
console.log(isAdultTernary); // true
The code is much cleaner, right? Ternary operators are especially handy for assigning values based on conditions.
Advantages of the Ternary Operator
- Conciseness: You can replace multiple lines of
if...elseblocks with just one line, improving code readability. - Expression-based: Since the ternary operator returns a value, you can use it not just for variable assignments but also directly as arguments in functions or within other expressions.
You Can Use It for Nested Conditions Too!
Ternary operators can also be chained together to handle multiple conditions, similar to else if statements:
const age = 15;
const message = age < 8 ? 'Child' :
age < 18 ? 'Teenager' :
'Adult';
console.log(message); // 'Teenager'
However, chaining too many ternary operators can make code hard to read, so it’s best to limit them to 2–3 conditions. For more complex scenarios, using if...else or switch statements might be a better choice.
2. Optional Chaining: object?.property
Optional chaining (?.) is a relatively new feature introduced in ES2020 (ES11) and has quickly become a favorite tool for real-world programming. It allows you to safely access nested object properties without throwing an error if a property or its parent is null or undefined. Instead, it simply returns undefined.
Imagine a situation where you’re fetching user data from a server and want to access the user’s profile picture:
const user = {
name: 'Joy',
// The profile object might not exist
};
// Without optional chaining
// const profileImage = user.profile.image; // TypeError: Cannot read properties of undefined (reading 'image')
In this code, user.profile is undefined, so trying to access image results in a TypeError that could crash your application.
Previously, developers used if statements or logical AND (&&) operators to prevent such errors:
// 1. Using an if statement
let profileImage;
if (user && user.profile) {
profileImage = user.profile.image;
}
// 2. Using && operators
const profileImageAnd = user && user.profile && user.profile.image;
With optional chaining, this can be simplified dramatically:
const user = {
name: 'Joy',
};
const profileImage = user.profile?.image;
console.log(profileImage); // undefined (no error)
Since user.profile is undefined, the ?. operator stops further evaluation and returns undefined. No runtime error, no problem! Optional chaining also works for accessing array elements (arr?.[index]) and calling functions (func?.()), making it highly versatile.
3. Nullish Coalescing: value1 ?? value2
Nullish coalescing (??), often called the “nullish operator,” was also introduced in ES2020. It returns the right-hand value only if the left-hand value is null or undefined, unlike the logical OR operator (||), which returns the right-hand value for any “falsy” value.
This makes it incredibly useful for setting default values without unintentionally overwriting valid ones like 0 or "".
Difference Between || and ??
The OR operator (||) considers any “falsy” value—such as null, undefined, 0, "" (empty string), false, or NaN—and returns the right-hand value. This can cause bugs when 0 or "" is a valid input:
let height = 0;
console.log(height || 100); // 100
// height is falsy, so 100 is returned. Not the intended behavior.
With the nullish coalescing operator (??), only null and undefined are considered invalid, so the intended value is preserved:
let height = 0;
let text = "";
console.log(height ?? 100); // 0 (height is not null or undefined, so it's returned)
console.log(text ?? 'Default'); // "" (text is not null or undefined, so it's returned)
let missingValue = null;
console.log(missingValue ?? 'Default'); // 'Default'
This makes ?? the better choice when you want to keep falsy values like 0 or "" intact while providing a fallback for null or undefined.
Be Careful with Operator Precedence
When combining ?? with other logical operators (&&, ||), you must use parentheses to avoid syntax errors. This ensures clarity and prevents unintended behavior:
// let x = 1 && 2 ?? 3; // SyntaxError!
let x = (1 && 2) ?? 3; // Correct usage
console.log(x); // 2
In Summary: Get Comfortable with the Question Mark
We’ve covered the three key uses of the question mark (?) in JavaScript:
- Ternary Operator (
? :): Use it to simplifyif...elsestatements for assigning values based on conditions. - Optional Chaining (
?.): Use it to safely access nested properties without worrying aboutnullorundefinederrors. - Nullish Coalescing (
??): Use it to set default values while preserving valid falsy values like0or"".
These features are essential for writing modern JavaScript that’s both clean and robust. They may seem unfamiliar at first, but with a little practice, you’ll find them indispensable for improving code readability and reliability. Start replacing those lengthy if statements and clunky chains with these sleek question mark operators today!