Javascript

Shortening Javascript Expressions With The Optional Chaining and Null Coalescing Operators

Shortening Javascript Expressions With The Optional Chaining and Null Coalescing Operators

Modern JavaScript (ES2020+) gave us three powerful operators that make our code shorter, safer, and cleaner which are the optional chaining, null coalescing and null coalescing assignment operators.

 

 

 

Usually when dealing with object properties in Javascript, we check for existence of specific property, or checking if this property not nullable, by using ternary expressions. However when properties deeply nested inside the object, we tend to do multiple checks depending on nesting level of properties.

For this (ES2020+) give us three powerful operators that make our code shorter, safer, and cleaner:

  • ?. Optional Chaining

  • ?? Nullish Coalescing

  • ??= Nullish Coalescing Assignment

If you’ve ever written a pile of if checks or ternary operators to guard against undefined or null, these are for you.

1. Optional Chaining ?.

Problem Before

Accessing nested properties was risky:

// Throws error if user or user.address is undefined
const street = user.address.street;

You had to do:

const street = user && user.address ? user.address.street : undefined;

Modern Solution

const street = user?.address?.street;
  • If user or user.address is null or undefined, the whole expression evaluates to undefined instead of throwing.

  • Works with:

    • Property access: obj?.prop

    • Array indexing: arr?.[0]

    • Function calls: obj?.method?.()

Examples:
const arr = null;
console.log(arr?.[0]); // undefined, no crash

const obj = { greet: () => "Hi" };
console.log(obj?.greet?.()); // "Hi"
console.log(obj?.bye?.());   // undefined, no crash

 

2. Null Coalescing ??

Problem Before

We often want a default value only if something is null or undefined — but not for falsy values like 0 or "".

Using || can be wrong:

const count = 0;
const total = count || 10; // 10 (oops, 0 was replaced)

Modern Solution

const count = 0;
const total = count ?? 10; // 0 (correct)
  • ?? only falls back to the right-hand value if the left is null or undefined.

  • Keeps valid falsy values like 0, false, and "".

Example with optional chaining:

const name = user?.profile?.name ?? "Anonymous";

3. Nullish Coalescing Assignment ??=

This is like ?? but for assignment.

Problem Before

if (settings.theme == null) {
  settings.theme = "light";
}

Modern Solution

settings.theme ??= "light";
  • Assigns "light" to settings.theme only if it’s currently null or undefined.

  • Leaves other falsy values intact.

  • Suitable if you need to assign default values for object properties.
Examples
 
let opts = { debug: false };

opts.debug ??= true;  
console.log(opts.debug); // false (kept because not null/undefined)

opts.level ??= 1;
console.log(opts.level); // 1 (assigned because undefined)

Putting It All Together

Old Style Code:

const location = {
  District: selectedLocation && selectedLocation.selectedDistrict
    ? selectedLocation.selectedDistrict.id
    : ""
};

Modern Style Code:

const location = {
  District: selectedLocation?.selectedDistrict?.id ?? ""
};

And if you’re initializing defaults:

location.District ??= "Unknown";

 

Feature Old Way Modern Way
Safe nested access obj && obj.prop && obj.prop.x obj?.prop?.x
Default when null/undefined obj.prop != null ? obj.prop : fallback obj.prop ?? fallback
Assign default if null/undefined if (obj.prop == null) obj.prop = fallback; obj.prop ??= fallback

 

0 0 votes
Article Rating

What's your reaction?

Excited
0
Happy
0
Not Sure
0
Confused
0

You may also like

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments