JavaScript Optional Chaining (?.) and Nullish Coalescing (??) with null and undefined

TypeError: Cannot read properties of undefined is probably the most common JavaScript error of all time. It happens when code reads a property of something that is not there, such as a field missing from an API response. Modern JavaScript has two operators made for this: optional chaining ?. reads a value safely, and nullish coalescing ?? supplies a default only when the value is really missing. In this lesson you will learn both, the difference between ?? and ||, and the logical assignment operators.

Advertisement

📖 What You’ll Learn: where null and undefined come from, the “Cannot read properties of undefined” error, optional chaining for properties, brackets and method calls, nullish coalescing and how it differs from ||, combining ?. and ??, logical assignment (??=, ||=, &&=), and when not to use them.


💥 The Error These Operators Prevent

null and undefined have no properties. Reading a property from either one throws a TypeError and stops the program:

📄 crash.js

const response = { user: { name: "Asha" } };   // no "address" field

console.log(response.user.name);
console.log(response.address);                 // missing property: undefined
console.log(response.address.city);            // reading a property OF undefined: crash

⌨️ Terminal

node crash.js

🖥️ Output

Asha
undefined
/home/you/js-course/crash.js:5
console.log(response.address.city);            // reading a property OF undefined: crash
                             ^

TypeError: Cannot read properties of undefined (reading 'city')
    at Object.<anonymous> (/home/you/js-course/crash.js:5:30)

Node.js v26.13.0

The message says exactly what happened: the code tried to read city from a value that is undefined. Missing values come from many places:

  • API fields that are optional or null.
  • Array elements that do not exist (items[10] on a 3-item list).
  • Function parameters the caller did not pass.
  • find() and similar methods when nothing matches (they return undefined).
  • DOM lookups such as document.querySelector() that find nothing (they return null).

🔗 Optional Chaining (?.)

Definition: the optional chaining operator ?. reads a property only if the value on its left is not null or undefined. If it is, the whole expression stops (“short-circuits”) and returns undefined instead of throwing.

📄 optional-chaining.js

const response = { user: { name: "Asha", address: null }, items: [] };

console.log(response.user?.name);              // "Asha"
console.log(response.user?.address?.city);     // address is null -> undefined
console.log(response.profile?.avatar?.url);    // profile missing -> undefined
console.log(response.items?.[0]?.price);       // brackets: no first item -> undefined

⌨️ Terminal

node optional-chaining.js

🖥️ Output

Asha
undefined
undefined
undefined

Optional chaining has three forms:

FormExampleMeaning
Propertyobj?.propRead prop if obj exists
Bracketobj?.[key], arr?.[0]Read a computed key or index if obj/arr exists
Callfn?.(), obj.method?.()Call the function only if it exists

📄 forms.js

const logger = { info: (msg) => console.log("INFO:", msg) };

logger.info?.("test started");      // method exists: called
logger.debug?.("details");          // method missing: skipped, no error

const field = "email";
const user = { email: "qa@sqatools.in" };
const guest = null;
console.log(user?.[field], guest?.[field]);

⌨️ Terminal

node forms.js

🖥️ Output

INFO: test started
qa@sqatools.in undefined

⚠️ Watch out: ?. only protects against null and undefined. It does not help if the value exists but is the wrong type: "text"?.toFixed() still throws because strings have no toFixed method.


Advertisement

🧩 Nullish Coalescing (??)

Definition: the nullish coalescing operator a ?? b returns a if it is not null or undefined, and b otherwise. “Nullish” means exactly those two values.

📄 nullish.js

const settings = { timeout: 0, retries: null, title: "" };

console.log(settings.timeout ?? 30000);   // 0 is a real value: kept
console.log(settings.retries ?? 2);       // null: default used
console.log(settings.headless ?? true);   // missing: default used
console.log(JSON.stringify(settings.title ?? "Untitled")); // "" is a real value: kept

⌨️ Terminal

node nullish.js

🖥️ Output

0
2
true
""

?? vs ||

Before ?? existed, people wrote defaults with ||. But || uses truthiness, so it also replaces 0, "", false and NaN, which are often valid values:

📄 or-vs-nullish.js

const config = { timeout: 0, headless: false, prefix: "" };

console.log("||:", config.timeout || 30000, config.headless || true, JSON.stringify(config.prefix || "test-"));
console.log("??:", config.timeout ?? 30000, config.headless ?? true, JSON.stringify(config.prefix ?? "test-"));

⌨️ Terminal

node or-vs-nullish.js

🖥️ Output

||: 30000 true "test-"
??: 0 false ""
Left valuevalue || "default"value ?? "default"
undefined“default”“default”
null“default”“default”
0“default”0
""“default”“”
false“default”false
NaN“default”NaN

💡 Tip: Use ?? for defaults of settings and data (numbers, booleans, strings that may be empty). Use || only when every falsy value should really be replaced, for example an empty search term that should fall back to “all”.


🤝 Combining ?. and ??

The two operators work best together: ?. reaches into nested data safely, and ?? replaces a missing result with a sensible default.

📄 combined.js

const orders = [
  { id: 1, customer: { name: "Asha", address: { city: "Pune" } }, discount: 0 },
  { id: 2, customer: { name: "Ravi" } },
  { id: 3 },
];

for (const order of orders) {
  const name = order.customer?.name ?? "Guest";
  const city = order.customer?.address?.city ?? "Unknown city";
  const discount = order.discount ?? "none";
  console.log(`#${order.id} ${name} - ${city} - discount: ${discount}`);
}

⌨️ Terminal

node combined.js

🖥️ Output

#1 Asha - Pune - discount: 0
#2 Ravi - Unknown city - discount: none
#3 Guest - Unknown city - discount: none

Mixing ?? directly with || or && is not allowed, because the intended order would be ambiguous. Add parentheses:

📄 mixing.js

const a = null, b = 0;
const result = a ?? b || 5;
console.log(result);

⌨️ Terminal

node mixing.js

🖥️ Output

/home/you/js-course/mixing.js:2
const result = a ?? b || 5;
                      ^^

SyntaxError: Unexpected token '||'

Node.js v26.13.0

📄 mixing-fixed.js

const a = null, b = 0;
console.log((a ?? b) || 5);
console.log(a ?? (b || 5));

⌨️ Terminal

node mixing-fixed.js

🖥️ Output

5
5

Advertisement

✍️ Logical Assignment: ??=, ||= and &&=

Logical assignment operators combine a check with an assignment (ES2021):

OperatorSame asAssigns when
a ??= ba ?? (a = b)a is null or undefined
a ||= ba || (a = b)a is falsy
a &&= ba && (a = b)a is truthy

📄 logical-assignment.js

const options = { retries: 0, baseURL: undefined, token: "abc123" };

options.retries ??= 2;           // 0 is kept
options.baseURL ??= "https://sqatools.in";
options.workers ??= 4;           // new property added
options.token &&= `Bearer ${options.token}`; // only changed if a token exists

console.log(options);

⌨️ Terminal

node logical-assignment.js

🖥️ Output

{
  retries: 0,
  baseURL: 'https://sqatools.in',
  token: 'Bearer abc123',
  workers: 4
}

A typical use is filling in defaults for a configuration object without overwriting values the user did provide.


🧪 Tester Scenario: Read an Unreliable API Response

Search APIs often omit empty fields. This function turns each raw result into a clean row for a report, without crashing on missing data:

📄 api-report.js

const apiResponse = {
  data: {
    results: [
      { sku: "P-1", title: "Pen", price: { amount: 10, currency: "INR" }, rating: 4.5 },
      { sku: "P-2", title: "Notebook", price: null, rating: 0 },
      { sku: "P-3", title: "Lamp" },
    ],
  },
};

const rows = (apiResponse.data?.results ?? []).map((item) => ({
  sku: item.sku,
  title: item.title ?? "(no title)",
  price: item.price?.amount ?? "N/A",
  currency: item.price?.currency ?? "-",
  rating: item.rating ?? "not rated",
}));

console.table(rows);

const firstOutOfStock = apiResponse.data?.results?.find((r) => r.stock === 0);
console.log("First out-of-stock SKU:", firstOutOfStock?.sku ?? "none");

⌨️ Terminal

node api-report.js

🖥️ Output

┌─────────┬───────┬────────────┬───────┬──────────┬─────────────┐
│ (index) │ sku   │ title      │ price │ currency │ rating      │
├─────────┼───────┼────────────┼───────┼──────────┼─────────────┤
│ 0       │ 'P-1' │ 'Pen'      │ 10    │ 'INR'    │ 4.5         │
│ 1       │ 'P-2' │ 'Notebook' │ 'N/A' │ '-'      │ 0           │
│ 2       │ 'P-3' │ 'Lamp'     │ 'N/A' │ '-'      │ 'not rated' │
└─────────┴───────┴────────────┴───────┴──────────┴─────────────┘
First out-of-stock SKU: none
  • apiResponse.data?.results ?? [] guarantees an array, so map always works.
  • The rating 0 is kept because ?? only replaces null/undefined. With || it would wrongly show “not rated”.
  • find() returns undefined when nothing matches, and ?.sku ?? "none" handles that.

⚠️ Watch out: In tests, do not use ?. and ?? to hide data that must be present. If the API contract says price is required, assert that it exists (expect(item.price).toBeDefined()) so the test fails and reports the defect, instead of printing “N/A”.


Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Safely print the city from const user = { profile: null }, printing Unknown when it is missing.

Show answer

📄 practice1.js

const user = { profile: null };
console.log(user.profile?.address?.city ?? "Unknown");

🖥️ Output

Unknown

Q2. Predict the output of each line, then run it.

console.log(0 || 10);
console.log(0 ?? 10);
console.log("" || "x");
console.log("" ?? "x");
console.log(null ?? false ?? "z");
Show answer

📄 practice2.js

console.log(0 || 10);
console.log(0 ?? 10);
console.log("" || "x");
console.log("" ?? "x");
console.log(null ?? false ?? "z");

🖥️ Output

10
0
x

false

In the last line, null ?? false gives false, which is not nullish, so the chain stops there.

Q3. Write getRetries(config) that returns config.retries if it was set (including 0), otherwise 2. It must also work when config itself is undefined.

Show answer

📄 practice3.js

function getRetries(config) {
  return config?.retries ?? 2;
}

console.log(getRetries({ retries: 0 }));
console.log(getRetries({ retries: 5 }));
console.log(getRetries({}));
console.log(getRetries(undefined));

🖥️ Output

0
5
2
2

Q4. Call hooks.onFinish() only if it exists, for both hooks = { onFinish: () => console.log("done") } and hooks = {}.

Show answer

📄 practice4.js

const withHook = { onFinish: () => console.log("done") };
const withoutHook = {};

withHook.onFinish?.();
withoutHook.onFinish?.();
console.log("no error");

🖥️ Output

done
no error

Q5. Fill in defaults with ??=: browser should default to "chromium" and headless to true, but an explicit headless: false must be kept.

Show answer

📄 practice5.js

const run = { headless: false };
run.browser ??= "chromium";
run.headless ??= true;
console.log(run);

🖥️ Output

{ headless: false, browser: 'chromium' }

Q6. From const tests = [{ name: "login", tags: ["smoke"] }, { name: "search" }], print each test with its first tag, or untagged.

Show answer

📄 practice6.js

const tests = [{ name: "login", tags: ["smoke"] }, { name: "search" }];
for (const t of tests) {
  console.log(`${t.name}: ${t.tags?.[0] ?? "untagged"}`);
}

🖥️ Output

login: smoke
search: untagged

🧠 MCQ Quiz: Optional Chaining and Nullish Coalescing

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What does user?.address?.city return when user.address is null?
  2. What is 0 ?? 5?
  3. What is 0 || 5?
  4. Which values count as “nullish”?
  5. How do you call a method only if it exists?
  6. What happens with null ?? 0 || 1?
  7. What does items?.[0] do when items is undefined?
  8. After let a = 0; a ??= 10; what is a?
  9. After let b = 0; b ||= 10; what is b?
  10. What error does undefined.name throw?

💼 Interview Questions and Answers

Q1. What is the difference between ?? and ||?

a || b returns b whenever a is falsy (false, 0, "", NaN, null, undefined). a ?? b returns b only when a is null or undefined. Use ?? for defaults when 0, empty strings or false are valid values, such as a timeout of 0 or headless: false.

Q2. How does optional chaining short-circuit?

If the value before ?. is nullish, evaluation of the whole chain stops and the result is undefined; later property reads and function calls in that chain, including their arguments, are not evaluated.

📄 short-circuit.js

let calls = 0;
const count = () => ++calls;
const user = null;

console.log(user?.profile.getName(count()));
console.log("count() was called", calls, "times");

⌨️ Terminal

node short-circuit.js

🖥️ Output

undefined
count() was called 0 times

Q3. You see “TypeError: Cannot read properties of undefined (reading ‘id’)” in a test. How do you debug it?

  1. Read the stack trace to find the exact line and the expression ending in .id.
  2. Identify which object was undefined: log or inspect each part of the chain (for example response.body, response.body.items[0]).
  3. Find why it is missing: wrong API response, an empty list, a missing await (you received a Promise), or a find() that matched nothing.
  4. Fix the cause. If the value is legitimately optional, use ?. and ??; if it is required, add an assertion that reports a clear message.

Q4. When should you not use optional chaining?

When the value is required. Writing order?.id everywhere hides bugs: the code keeps running with undefined and fails later, far from the cause, or a test passes while checking nothing. Use ?. for data that is genuinely optional, and let required data fail fast (or validate it at the boundary, for example when parsing an API response).

Q5. What do ??=, ||= and &&= do?

They are logical assignment operators (ES2021). a ??= b assigns b only if a is nullish; a ||= b only if a is falsy; a &&= b only if a is truthy. They short-circuit, so the assignment (and evaluating b) does not happen when the condition is not met. A common use is applying default options.


Advertisement

❓ Frequently Asked Questions

🤔 Which JavaScript versions support ?. and ???

Both were added in ES2020 and work in all current browsers and every supported Node.js version. Logical assignment (??=, ||=, &&=) arrived in ES2021.

🤔 Can I use optional chaining on the left side of an assignment?

No. user?.name = "Asha" is a SyntaxError. Check first, for example if (user) user.name = "Asha";.

🤔 Is optional chaining slower?

The cost is negligible. Choose it for clarity and safety where values are optional.

🤔 What is the difference between null and undefined here?

None: ?., ?? and ??= treat both as “missing”. Their difference matters elsewhere, as explained in the Data Types lesson.


🏁 Summary

  • Reading a property of null or undefined throws “Cannot read properties of undefined”.
  • ?. reads properties, indexes (?.[ ]) and calls (?.()) safely, returning undefined when the left side is nullish.
  • ?? supplies a default only for null/undefined, keeping valid 0, "" and false; || replaces every falsy value.
  • ??=, ||= and &&= assign conditionally; mixing ?? with || needs parentheses.
  • Use these operators for optional data, and assertions for required data.

Next, continue with Lesson 12: Operators. This completes Module 2. Module 3 continues with operators and control flow.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in