Stop missing data from crashing your page: JavaScript optional chaining ?. and nullish coalescing ??, explained plainly
One missing layer in your data can blank the whole order page. Following MDN's Optional chaining, Nullish coalescing, and Logical nullish assignment docs: the three forms of ?., short-circuiting, optional calls and bracket access, ?? vs || on 0 and empty strings, the ?. + ?? combination, the ban on mixing ?? with || and &&, and ??= defaults — with a 100-mistake breakdown from a fictional cafe order page.

First, the boundary of this guide. The site already has plenty of JavaScript basics guides: functions explain how to write functions, conditionals explain how to make decisions, loops explain how to repeat things, objects and destructuring explain how to take data apart, classes and the prototype chain explain how to write types, closures explain how long a variable lives, the event loop explains when code runs, Promises and async explain how to wait for asynchronous results, and try...catch explains what to do when something goes wrong. This guide covers none of those. It covers one thing: how to read a value without blowing up the page when a piece of the data is missing. The running example is "Greenstone Cafe", the same fictional practice project as before: a small order page for a street-side cafe. Earlier guides used it to show decisions, loops, and storage; this time it shows what goes wrong when reading data: some customer fields are filled in, some are not, and some things on an order exist while others do not. Everything shown with it — the operations, the code, and the numbers — is invented to explain the technique, not a real record. Every rule about optional chaining and nullish coalescing comes from MDN's three official docs, "Optional chaining (?.)", "Nullish coalescing operator (??)", and "Logical nullish assignment (??=)"; the sources are listed in each article's meta information and evidence record. By the end you should be able to do four things: safely read deeply nested properties and call methods that may not exist with ?., give missing values a default with ?? without clobbering 0 and the empty string, know that ?? cannot be mixed directly with || and &&, and fill in defaults on an object with ??=.
Step 1: First look at the problem — one missing layer breaks the whole page
The order page wants to show which city a customer lives in. The data looks like this: the order has a customer, the customer has an address, the address has a city. Written normally it is order.customer.address.city, one dot after another. But what if the customer never filled in an address? Then order.customer.address is undefined, and reading .city off it throws a TypeError: "Cannot read properties of undefined". Worse, the error happens halfway through rendering, so the whole order page can go blank, and the customer cannot even see what they already ordered. MDN puts it plainly: to read a deeply nested property, you have to confirm every layer in between exists, because reading it directly will throw. The old fix was to guard each layer with &&: order.customer && order.customer.address && order.customer.address.city. That works, but it gets wordy when the chain is long, and it has a hidden trap: && blocks not only null and undefined, but also 0 and the empty string, as explained later. ?. exists to solve this: it only cares whether something in the middle is null or undefined, and lets every other value through.
Step 2: What ?. is — learn all three forms at once
Optional chaining comes in three forms, one for each way of reading something. The first reads a property: obj?.prop. The second reads with brackets: obj?.[expr], where the brackets can hold a variable. The third calls a function: func?.(args). They all mean the same thing: if the thing on the left of ?. is null or undefined, the whole expression stops right there and returns undefined, without throwing; if the left side has a value, reading continues as normal. MDN's opening example makes the point:
const adventurer = {
name: "Alice",
cat: {
name: "Dinah",
},
};
const dogName = adventurer.dog?.name;
console.log(dogName);
// Expected output: undefined
console.log(adventurer.someNonExistentMethod?.());
// Expected output: undefined
Alice has a cat and no dog. adventurer.dog is undefined, and reading .name off it would normally throw; with ?. it simply gives undefined. Calling a method that does not exist is the same: no error, just undefined. The cat does exist, so adventurer.cat?.name normally gives "Dinah". Remember the test: ?. only recognizes two kinds of "missing", null and undefined. 0, the empty string, and false are also falsy values in JavaScript, but ?. does not treat them as missing: 0?.missing is undefined (because 0 genuinely has no such property, not because 0 was treated as empty), ""?.length is 0, and false?.missing is undefined. That is exactly where ?. beats &&: && stops at 0 and returns 0 itself as the result; ?. walks past 0 and only stops when something is truly missing.
Step 3: The chain can keep going — it stops wherever it breaks
The most common use of ?. is to write several in a row, guarding every layer of a deep chain. MDN's example about Carl works this way: Carl is 82, lives in "Paradise Falls", but his detailed address is unknown. The code that reads his city is customer.details?.address?.city: details exists, address does not, so the chain stops at address and the whole result is undefined, with no error. Give the same line a customer whose address is complete, and it returns the city normally. The cafe order page uses the same form:
const city = order.customer?.address?.city ?? "City not filled in";
// "City not filled in" when the customer left the address blank,
// "Hangzhou" when it is filled in
That line also sneaks in ??, the star of the next section; for now just read it as "use the value on the right when the left side is null or undefined". Short-circuiting has two details worth remembering. First, once the chain breaks, the rest is never even evaluated. MDN's example is potentiallyNullObj?.[x++]: the left side is null, so the x++ step is skipped entirely and x stays 0. Writing potentiallyNullObj?.a.b is the same: once it breaks at the first ?., the .b after it is never read, so nothing throws. Second, short-circuiting only travels along one continuous chain. Once you cut the chain with parentheses, the protection ends. (potentiallyNullObj?.a).b throws, because the ?. inside the parentheses evaluates first and gives undefined, and the .b outside the parentheses reads a property off undefined, outside the reach of ?.. My judgement is: treat ?. as one rope, and do not tie a knot in the middle with parentheses — a knot only protects the part before it.
Step 4: When a method may not exist, call it with ?.()
Reading a property can hit a missing piece, and so can calling a method. The order page talks to a third-party membership API: some versions have a method called customMethod, some do not. Calling someInterface.customMethod() directly throws on the versions that lack it. With someInterface.customMethod?.(), a missing method just gives undefined and the page keeps running. MDN also shows this with callbacks: a function takes an onError callback and calls it when something goes wrong, but the caller may never have passed one. The old way tests if (onError) first; the new way is one line: onError?.(err.message) — undefined when nothing was passed, a normal call when it was. Two traps to remember. First, ?.() only covers "the method does not exist", not "this thing is not a function": if customMethod exists but is the number 42, customMethod?.() still throws a TypeError, because 42 cannot be called. Second, ?. only guards the step on its own left: someInterface.customMethod?.() guards the customMethod step, so if someInterface itself is null it still throws. You have to write someInterface?.customMethod?.(), with ?. on both steps. The cafe example: an order has an optional note that is sometimes empty, and showing it in upper case is order.note?.toUpperCase() ?? "No note" — "No note" when there is no note, upper-case text when there is one.
Step 5: When the property name is a variable or a number index, use ?.[]
Use ?. when the property name is written out, and the bracket form ?.[] when the name lives in a variable or you want an element of an array by index. MDN's example puts a variable in as the property name: const propName = "x"; const nestedProp = obj?.[propName];. Array indexes can only be read with brackets, so they need this form even more:
function printMagicIndex(arr) {
console.log(arr?.[42]);
}
printMagicIndex([0, 1, 2, 3, 4, 5]); // undefined
printMagicIndex(); // undefined
The array has only 6 numbers, so the 42nd never existed and the answer is undefined; when no array is passed at all, arr is undefined, and the version without ?. would throw, while the version with ?. calmly gives undefined. MDN also has a Map example: only "JS" was stored, so reading the name for "CSS", myMap.get("CSS")?.name, gives undefined, while myMap.get("JS")?.name gives "Josh". The order page reads its first dish the same way: order.items?.[0]?.name ?? "Nothing ordered yet" — "Nothing ordered yet" when the order has no dishes, the first dish's name, such as "Latte", when it does. Note that the expression inside ?.[] follows the same short-circuit rule: once the chain breaks, the expression in the brackets is never evaluated, which is exactly what the x++ example in the previous section showed.
Step 6: What ?? is — a default only for values that are truly missing
?. answers "what if I cannot read it"; ?? answers "I read it, but it is empty — what do I use instead". The rule for ?? is a single sentence: when the left side is null or undefined, use the right side; when the left side is anything else, even 0, the empty string, or false, keep it exactly as it is. MDN's two opening examples say it all: null ?? "default string" gives "default string", because the left side is null; 0 ?? 42 gives 0, because 0 is neither null nor undefined, so 42 is never used. Then a set of contrasts:
const nullValue = null;
const emptyText = ""; // falsy
const someNumber = 42;
const valA = nullValue ?? "default for A";
const valB = emptyText ?? "default for B";
const valC = someNumber ?? 0;
console.log(valA); // "default for A"
console.log(valB); // "" (as the empty string is not null or undefined)
console.log(valC); // 42
The empty string is falsy, but it is not null, so valB stays an empty string and is not swapped for "default for B". That is the whole reason ?? exists. People used to fill in defaults with ||, as in foo || "Hello!", but || tests "is this falsy", and 0, the empty string, NaN, and false all get replaced by it. MDN works it out plainly: const qty = 0 || 42 gives 42, not 0; const message = "" || "hi!" gives "hi!", not the empty string. The tip on the order page is a live example: a customer who tips 0 means "no tip at all", and order.tip || 5 would wrongly turn that into 5, while order.tip ?? 5 keeps it 0. My judgement is: whenever 0, the empty string, or false is itself a legitimate meaning for a field, only ?? may fill in its default — using || quietly rewrites what the customer meant.
Step 7: ?. and ?? together — the combination the order page uses most
Each operator is useful alone; together they are the everyday pair. ?. reads safely and gives undefined when something is missing; ?? swaps that undefined for a sentence a person can read. MDN's example reads a property and upper-cases it: foo.someFooProp?.toUpperCase() ?? "not available" gives "HI" when the property is there and "not available" when it is not. MDN also writes the combination as a function:
function printCustomerCity(customer) {
const customerCity = customer?.city ?? "Unknown city";
console.log(customerCity);
}
printCustomerCity({
name: "Nathan",
city: "Paris",
}); // "Paris"
printCustomerCity({
name: "Carl",
details: { age: 82 },
}); // "Unknown city"
Nathan filled in Paris, so the answer is Paris; Carl filled in no city, so the answer is "Unknown city". The cafe order page is written entirely in this combination: "City not filled in" when no city was given, "No coupon" when there is no coupon, "Nothing ordered yet" when there is no first dish, "No note" when there is no note. ?? has one more short-circuit detail: when the left side is not null or undefined, the expression on the right is never evaluated at all. MDN's example uses three functions a, b, and c, each logging a line: in a() ?? c(), a returns undefined, so c is called too, the result is "foo", and the log reads "a was called" then "c was called"; in b() ?? c(), b returns false, false is not null, so c is never called, the result is false, and the log has only "b was called". This matches || and &&: the half you do not need is not computed, which saves work and is a good thing when the right side has side effects, such as sending a request or writing a log.
Step 8: The red line for ?? — never mix it directly with || or &&
?? has one hard red line: it cannot sit in the same expression as || or && without parentheses. Write it that way and you get a SyntaxError; the code will not even start. MDN's words are "it is not possible to combine either the AND (&&) or OR operators (||) directly with ??", and a syntax error is thrown in such cases:
null || undefined ?? "foo"; // raises a SyntaxError
true && undefined ?? "foo"; // raises a SyntaxError
To mix them, add parentheses and say what you mean: (null || undefined) ?? "foo" gives "foo". MDN does not spell out why the rule exists; my judgement is that ?? and || sit too close in precedence for a reader to tell at a glance which runs first, so the language simply refuses to let you write it and forces you to state it with parentheses. Remember where ?? sits in precedence, too: one level below || and one level above the ternary operator. In day-to-day code my habit is to parenthesize whenever ?? shares a line with ||, &&, or a ternary, even when it would run fine without them. Parentheses cost nothing, and every second a reader does not spend puzzling is a second saved. One more easy mistake: both sides of ?? are expressions, and the right side can be a function call — but as the last section showed, the right side never runs when the left side has a value, so never put an operation that must happen on the right of ??, such as value ?? saveDefault() expecting it to save every time. When the left side has a value it will not run once.
Step 9: ??= — filling in an object's defaults in one line
?? has an assignment cousin, ??=, which means "assign only when the left side is null or undefined, otherwise leave it alone". MDN's example:
const a = { duration: 50 };
a.speed ??= 25;
console.log(a.speed);
// Expected output: 25
a.duration ??= 10;
console.log(a.duration);
// Expected output: 50
speed did not exist, so it gets 25; duration was already 50, so ??= leaves it alone. The full meaning of x ??= y is x ?? (x = y), except the expression x is only evaluated once. Short-circuiting pays off here as well: when the left side is not nullish, the y on the right is never evaluated at all. MDN's example is x ??= console.log("y evaluated") with x equal to 1, which logs nothing. Even better, when no assignment happens, the assignment itself never happens: for a const variable x = 1, writing x ??= 2 does not throw, because the code never reaches the assignment; and for an object property with a setter, the setter is not triggered when the value is not nullish. MDN also shows the classic use, filling in configuration:
function config(options) {
options.duration ??= 100;
options.speed ??= 25;
return options;
}
config({ duration: 125 }); // { duration: 125, speed: 25 }
config({}); // { duration: 100, speed: 25 }
Pass 125 and it stays 125; pass nothing and both defaults are filled in. Compared with destructuring defaults, ??= covers one more case: when a property's value is null, a destructuring default does not apply (because the property "has a value", it is just null), while ??= does apply. The order page's default settings are written this way: settings.size ??= "Medium"; settings.sugar ??= 0; — a sugar value of 0 is the customer's explicit "no sugar", ??= will not change it, and writing settings.sugar ??= 5 a second time still leaves it 0.
Step 10: Three bans and a checklist
Finally, three bans, all written out in MDN. First, you cannot assign to the result of ?.: object?.property = 1 is a SyntaxError, because the result of ?. may be the undefined produced by short-circuiting, and assigning to undefined means nothing. Second, you cannot use ?. to build a new object or as a template literal tag: new Intl?.DateTimeFormat() and String.raw?.`Hello, world!` are both SyntaxErrors. Third, ?. cannot rescue a variable that was never declared: undeclaredVar?.prop is still a ReferenceError, because the variable does not exist at all, so there is no way even to ask whether it is null; but a declared variable whose value is undefined is fine, and ?. returns undefined normally. There is also a common beginner misunderstanding: ?. is not a universal shield. It only guards against null and undefined, not other errors. When a property exists but is not a function, ?.() still throws a TypeError; when parentheses cut the chain, everything outside the parentheses still throws. ?? is the same: it only cares whether a value exists, not whether the value is right — if a customer types gibberish as their city, ?? will not catch it. Here is the checklist for this guide, to run through line by line when writing value-reading code for the order page: is every step of a deep read guarded with ?., with no step missed; is a default filled in with ?? or with ||, and are 0 and the empty string legitimate values for this field; is ?? mixed with || or && anywhere without parentheses; is ??= used only where the rule is "fill in only when missing"; is the result of ?. ever placed on the left of an assignment or after new.
One more practical pass: rewrite every value read on the order page the way this guide teaches. Showing order details used to take four or five lines of checks: is the order there, is the customer there, is the address there, and only then read the city — and every missing check was one more chance for a blank page. Rewritten as order.customer?.address?.city ?? "City not filled in", it is one line, and it reads more clearly: if any step along the way is missing, show "City not filled in". Coupons, notes, and the first dish work the same way, one line of ?. plus ?? each. The place people forget is lists: every item in the order list reads item.drink?.name, and one item that cannot be read must not take down the whole list — ?. inside the loop body protects them all at once. Configuration is the other spot: the settings object the order page reads may be missing fields, so fill in the defaults with ??= right after reading it, and the code after that never has to test for emptiness again. Once the rewrite is done, sweep the old || defaults too: price, tip, sugar, and quantity are fields where 0 is a legitimate value, and the job is only finished once they all use ??.
The chart above shows the fictional Greenstone Cafe order page's 100 "could not read the value" failures in one month, broken down by cause: a middle layer of a deep property was undefined and a plain dot read threw an error, 28 times; 0 or an empty string was treated as missing by || and given the wrong default, 22 times; an optional method did not exist and was called without ?.(), 14 times; ?? mixed with || or && without parentheses threw a syntax error, 12 times; ?. was written on the left of an assignment, 9 times; the chain broke halfway and the later properties were assumed to have been read, 8 times; ? was added only at the end of the chain while a null at the start went unguarded, 7 times. 28 + 22 + 14 + 12 + 9 + 8 + 7 = 100, the books balance. The top two causes together are half of all failures, and both come from "not telling apart what counts as missing": one is not knowing a layer in the middle can be absent, the other is treating 0 and the empty string as absent too. Every category in the chart maps to a step in this guide: the first to Step 1, the second to Step 6, the third to Step 4, the fourth to Step 8, the fifth to Step 10, the sixth to Step 3, and the seventh to the "guard both steps" passage in Step 4. The next time the order page goes blank, check in that order — most cases are located within three minutes.
Looking back at the four things this guide promised: ?. lets a deep read return undefined calmly when something is missing, instead of throwing; ?? gives a default only to values that are truly missing, leaving 0 and the empty string alone; ?? mixed with || or && must be parenthesized, or it is a syntax error; and ??= turns "fill in only when missing" into one line of code, without evaluating the right-hand expression or triggering a setter. Together, the four symbols shrink the order page's value-reading code from a long string of && checks into single lines, and the meaning gets more precise, not less. The for...of from the loops guide will show up again: ?. and for...of do not conflict — one handles "can this be read", the other handles "how many times", and each does its own job. Once you finish this guide, search the order page for every || "default", and wherever 0 or the empty string is a legitimate meaning, swap it for ??. It is the cheapest small refactor you will do all week.
Comments (0)
Sources
Related articles
The main thread has to draw the page and do the accounts, so it freezes the moment the work gets heavy. A worker is another thread in another global context, and the two sides talk only through messages. Following MDN's Using Web Workers and Worker docs: new Worker, postMessage and onmessage, structured-clone copying, what a worker can and cannot do, onerror and terminate(), SharedWorker, and transferable zero-copy — with a 100-mistake breakdown from a fictional cafe order page.
setTimeout handles once, setInterval handles repeatedly — but delay only promises "at least this long": 0 is not immediate, background tabs run even later, and anything over 2147483647 overflows. Following MDN's setTimeout and setInterval docs: async return, argument passing, the delay rules, the 4 ms nesting clamp, clearTimeout and clearInterval, recursive setTimeout, lost this, and string arguments — with a 100-mistake breakdown from a fictional cafe order page.
An array has to be computed all at once; a generator hands out one value at a time, only when asked. Following MDN's Iterators and generators, function*, and Generator docs: the next() protocol, function* and yield, for...of consumption, Symbol.iterator, yield* delegation, sending values in with next(x), throw() and return(), and when to use a generator at all — with a 100-mistake breakdown from a fictional cafe order page.