Himanshu SharmaSoftware engineer
Let’s talk

JavaScript · Lesson 57 of 58

Optional chaining and other modern syntax

Write safer, shorter JavaScript with optional chaining, nullish coalescing, logical assignment, spread, structuredClone and newer array methods.

12 minModern JavaScript and projectUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonUse optional chaining, ?? and logical assignment to handle missing data, and recognise the handy modern methods that replace older patterns.

After this lesson you can read and write the modern syntax found in most current JavaScript, especially the three operators that make handling missing data far less painful: ?., ?? and ??=.

JavaScript gets a new edition every year. Most additions are small conveniences. This lesson picks the ones you are most likely to use or meet in other people's code. For the newest items, check the support tables for your target browsers before depending on them; the operators in the first half have been well supported in current browsers for several years.

Optional chaining: ?.

Real data has holes. A user may have no address, and the address may have no city. Reading a property of undefined throws a TypeError, so you used to write long && chains. Optional chaining shortens that.

html
<pre id="out"></pre>
<script>
  const out = document.getElementById("out");
  const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };

  const user = {
    name: "Asha",
    address: { city: "Pune" },
    tags: ["a"],
    greet() { return "hi"; }
  };

  log("city:", user.address?.city);
  log("work city:", String(user.work?.city));
  log("deeper:", String(user.work?.address.city));
  log("first tag:", user.tags?.[0]);
  log("missing list:", String(user.missing?.[0]));
  log("method:", user.greet?.());
  log("no method:", String(user.nope?.()));
</script>
result
city: Pune
work city: undefined
deeper: undefined
first tag: a
missing list: undefined
method: hi
no method: undefined

There are three forms: obj?.prop for a property, obj?.[key] for a computed key or index, and fn?.() to call a function only if it exists. If the value before ?. is null or undefined, the whole rest of the chain is skipped and the result is undefined. That is why user.work?.address.city is safe even though address has no ?. of its own: the chain stopped at work.

Without it, user.work.city throws Cannot read properties of undefined (reading 'city').

Use it where data is truly optional, such as an API field that may be missing. Do not sprinkle it everywhere: if a value must exist, a loud error is better than a silent undefined, because it points straight at the bug.

Nullish coalescing: ??

a ?? b gives b only when a is null or undefined. It looks like ||, but there is an important difference, which you met in Ternary, &&, || and ??:

javascript
console.log(0 ?? 10);        // 0
console.log("" ?? "x");      // (an empty string)
console.log(null ?? "dflt"); // dflt
console.log(undefined ?? "dflt"); // dflt
console.log(false ?? true);  // false

console.log(0 || 10);        // 10
console.log("" || "x");      // x

When a setting of 0 is valid, for example a volume or a count, || wrongly replaces it with the default. ?? keeps it. It combines naturally with optional chaining: const city = user.address?.city ?? "Unknown";.

Logical assignment: ??=, ||= and &&=

These combine a check and an assignment:

javascript
let a = null;
a ??= 5;     // a was null, so it becomes 5
let b = 0;
b ||= 7;     // b was falsy, so it becomes 7
let c = 1;
c &&= 9;     // c was truthy, so it becomes 9
console.log(a, b, c); // 5 7 9

x ??= value means "if x is null or undefined, set it". It is great for default values, such as options.retries ??= 3.

Spread, rest and destructuring in objects

You met ... in Rest and spread and Destructuring. With objects, spread makes a shallow copy and lets you override:

javascript
const o = { a: 1, b: 2 };
const o2 = { ...o, b: 3, c: 4 };
console.log(o2); // { a: 1, b: 3, c: 4 }

const { a: x, z = "def", ...rest } = { a: 1, q: 2, r: 3 };
console.log(x, z, rest); // 1 def { q: 2, r: 3 }

Later properties win, so order matters. Spread is shallow: nested objects are shared, not copied. For a full independent copy, use structuredClone:

javascript
const copy = structuredClone({ d: [1, { e: 2 }] });
console.log(copy); // { d: [ 1, { e: 2 } ] }

It handles nested objects, arrays, dates and maps, but throws on functions.

Small helpers worth knowing

javascript
const arr = [1, 2, 3, 4];
console.log(arr.at(-1));            // 4    last item
console.log("hello".at(-2));        // l    works on strings too

console.log(Object.entries({ a: 1, b: 2 }));          // [ [ 'a', 1 ], [ 'b', 2 ] ]
console.log(Object.fromEntries([["a", 1], ["b", 2]])); // { a: 1, b: 2 }

console.log([1, [2, [3]]].flat());          // [ 1, 2, [ 3 ] ]
console.log([1, [2, [3]]].flat(Infinity));  // [ 1, 2, 3 ]
console.log([1, 2].flatMap(n => [n, n * 10])); // [ 1, 10, 2, 20 ]

console.log("a-b-c".replaceAll("-", "+"));  // a+b+c
console.log(Object.hasOwn({ q: 1 }, "q"));  // true
console.log(1_000_000, 2 ** 10);            // 1000000 1024

Numeric separators (1_000_000) make long numbers readable, and ** is the power operator.

Newer array methods that do not mutate

The classic sort() and reverse() change the array they are called on, a regular source of bugs. Newer methods return a new array and leave the original alone:

javascript
const orig = [3, 1, 2];
console.log(orig.toSorted());     // [ 1, 2, 3 ]
console.log(orig.toReversed());   // [ 2, 1, 3 ]
console.log(orig.with(1, 9));     // [ 3, 9, 2 ]
console.log(orig);                // [ 3, 1, 2 ]  unchanged
console.log([1, 2, 3, 4].findLast(n => n % 2 === 1)); // 3

toSorted, toReversed, with and findLast arrived over 2022 and 2023 and are available in current browsers, but older ones lack them. The ES2024 additions Object.groupBy and Promise.withResolvers are newer still. Look at a compatibility table, such as the one on MDN's pages for each feature, before using them on a site that must support old devices.

javascript
console.log(Object.groupBy([1, 2, 3, 4], n => (n % 2 ? "odd" : "even")));
// { odd: [ 1, 3 ], even: [ 2, 4 ] }

The result has no prototype, so Node prints it with a [Object: null prototype] label.

Common mistakes

  • Using || for defaults when 0 or an empty string is valid. Use ??.
  • Overusing ?.. It hides real bugs by turning them into quiet undefined values. Use it only for data that may legitimately be missing.
  • Mixing ?? with || or && without brackets. JavaScript refuses a || b ?? c as a syntax error. Add parentheses.
  • Thinking spread makes a deep copy. Nested objects are still shared. Use structuredClone when you need independence.
  • Assigning to the result of ?.. user?.name = "x" is a syntax error.
  • Using brand-new methods without checking support. Your page may break for visitors on older browsers.
  • Mutating with sort() by accident. Copy first with [...arr].sort() or use toSorted().

Exercise

Given const data = { user: { profile: null }, settings: { volume: 0 } }; write one line each that: reads data.user.profile.name safely with the default "Guest"; reads data.settings.volume with a default of 50 that correctly keeps the 0; sets data.settings.theme to "light" only if it is not already set; and makes an independent deep copy of data and proves that changing the copy does not change the original.

Next up is the course finale, where you combine nearly everything you learned: the final project lesson, a to-do app.

Key points

  • Optional chaining (?.) stops and returns undefined when the value before it is null or undefined.
  • Nullish coalescing (??) supplies a default only for null or undefined, so 0, an empty string and false are kept.
  • Logical assignment (??=, ||=, &&=) assigns only when a condition on the left is met.
  • Spread copies arrays and objects, and structuredClone makes a deep copy.
  • Newer methods such as at, flat, toSorted and Object.groupBy replace older tricks, but check browser support for the newest.

Check yourself

1. What does user.work?.city return when user.work is undefined?
2. What is the value of 0 ?? 10?
3. After let n = null; n ??= 5; what is n?
4. Which call copies an object including everything nested inside it?
5. Does [3, 1, 2].toSorted() change the original array?