Lesson 74 of 296
Optional chaining, nullish coalescing, getters and setters
What you will learn
- Optional chaining
?.in all its forms - Nullish coalescing
??and why it is better than||for defaults - Logical assignment operators
??=,||=,&&= - Getters and setters in objects and classes
On this page
Optional chaining ?.
?. reads a property only if the value before it is not null or undefined. Otherwise it stops and returns undefined instead of throwing an error.
const user = { profile: null };
user.profile.name TypeError: Cannot read properties of null
user.profile?.name undefined
user.settings?.theme undefinedThree forms:
| Form | Example | Use |
|---|---|---|
| Property | obj?.prop | Read a property |
| Bracket | obj?.[key] and arr?.[0] | Dynamic key or array index |
| Call | fn?.() and obj.method?.() | Call only if the function exists |
const city = order?.customer?.address?.city;
const first = response?.items?.[0];
options.onSuccess?.(result); call the callback only if it was givenShort-circuit: once ?. finds null or undefined, the whole rest of the chain is skipped.
Do not overuse it. If a value should always exist, a missing value is a bug. Using ?. everywhere hides those bugs. Use it for data that is genuinely optional.
?. cannot be used on the left side of an assignment: user?.name = "Sam" is a SyntaxError.
Nullish coalescing ??
a ?? b returns b only when a is null or undefined. Otherwise it returns a.
| Expression | || result | ?? result |
|---|---|---|
0 ?? 10 vs 0 || 10 | 10 | 0 |
"" ?? "N/A" vs "" || "N/A" | "N/A" | "" |
false ?? true vs false || true | true | false |
null ?? 5 vs null || 5 | 5 | 5 |
undefined ?? 5 vs undefined || 5 | 5 | 5 |
Use ?? for default values whenever 0, "" or false are valid:
const volume = settings.volume ?? 50; a saved volume of 0 is kept
const pageSize = Number(query.size) || 20; here || is right: NaN and 0 are not valid sizesCombined:
const city = user?.address?.city ?? "Unknown";Mixing rule: you cannot mix ?? with && or || without brackets. a || b ?? c is a SyntaxError. Write (a || b) ?? c.
Logical assignment
| Operator | Means | Assigns when |
|---|---|---|
a ??= b | a ?? (a = b) | a is null or undefined |
a ||= b | a || (a = b) | a is falsy |
a &&= b | a && (a = b) | a is truthy |
config.timeout ??= 5000; set a default only if missing
cache[key] ??= computeValue(); compute only onceGetters and setters
A getter is a method that runs when you read a property. A setter is a method that runs when you assign to it. From outside, they look like normal properties.
In an object:
const user = {
firstName: "Sam",
lastName: "Khan",
get fullName() {
return `${this.firstName} ${this.lastName}`;
},
set fullName(value) {
const [first, last] = value.split(" ");
this.firstName = first;
this.lastName = last;
}
};
user.fullName; "Sam Khan" (no brackets)
user.fullName = "Ali Ahmed";
user.firstName; "Ali"In a class, with validation:
class Product {
#pricePence = 0;
get pricePence() {
return this.#pricePence;
}
set pricePence(value) {
if (!Number.isInteger(value) || value < 0) {
throw new RangeError("Price must be a whole number of pence, 0 or more");
}
this.#pricePence = value;
}
get priceLabel() {
return `£${(this.#pricePence / 100).toFixed(2)}`;
}
}
const p = new Product();
p.pricePence = 1999;
p.priceLabel; "£19.99"
p.pricePence = -5; RangeErrorUses:
- Computed values that are always up to date (
fullName,area,total). - Validation before changing data.
- Read-only properties: a getter with no setter. Assigning to it is ignored (or a TypeError in strict mode).
Keep getters fast and free of side effects. Code that reads a property does not expect it to do heavy work or change things.
Object.defineProperty is the lower-level way to define getters, setters and other property settings. Libraries like Vue use getters and setters (and Proxies) to detect data changes.
Common mistakes
- Using
?.on everything and hiding real bugs. - Using
||for defaults when 0 or "" are valid. - Mixing
??and||without brackets. - A setter that assigns to its own name (
set price(v) { this.price = v; }), which calls itself forever and causes a stack overflow. Store the value in a different (often private) field. - Calling a getter with brackets:
user.fullName()is a TypeError.
How to say it in an interview
"Optional chaining short-circuits to undefined when the value before it is null or undefined, for properties, brackets and function calls; I use it only for data that is genuinely optional. Nullish coalescing falls back only on null or undefined, unlike OR, which also replaces zero, empty string and false. Logical assignment like ??= sets a default only when needed. Getters and setters let me expose computed or validated values as properties, for example validating a price in a class setter with a private field."
Key words
| Word | Meaning |
|---|---|
Optional chaining ?. | Safe access that returns undefined instead of throwing |
Nullish coalescing ?? | A default only for null or undefined |
| Logical assignment | ??=, ||=, &&= |
| Getter | A method that runs when a property is read |
| Setter | A method that runs when a property is assigned |
| Computed property | A value calculated when read |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.