Skip to the content

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        undefined

Three forms:

FormExampleUse
Propertyobj?.propRead a property
Bracketobj?.[key] and arr?.[0]Dynamic key or array index
Callfn?.() 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 given

Short-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 || 10100
"" ?? "N/A" vs "" || "N/A""N/A"""
false ?? true vs false || truetruefalse
null ?? 5 vs null || 555
undefined ?? 5 vs undefined || 555

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 sizes

Combined:

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

OperatorMeansAssigns when
a ??= ba ?? (a = b)a is null or undefined
a ||= ba || (a = b)a is falsy
a &&= ba && (a = b)a is truthy
config.timeout ??= 5000;        set a default only if missing
cache[key] ??= computeValue();  compute only once

Getters 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;     RangeError

Uses:

  • 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

WordMeaning
Optional chaining ?.Safe access that returns undefined instead of throwing
Nullish coalescing ??A default only for null or undefined
Logical assignment??=, ||=, &&=
GetterA method that runs when a property is read
SetterA method that runs when a property is assigned
Computed propertyA value calculated when read

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.