Example 1 — Optional call
fn?.() only calls if fn exists.
JavaScript
const fn = null;
console.log(fn?.(1)); How It Works
- fn is null, so call is skipped.
Optional chaining ?. stops and returns undefined if the value before it is null or undefined, instead of throwing.
const user = { profile: { city: "London" } };
console.log(user.profile?.city);
console.log(user.address?.city); fn?.() only calls if fn exists.
const fn = null;
console.log(fn?.(1)); arr?.[0] for maybe-arrays.
const arr = null;
console.log(arr?.[0]); Default when missing.
const city = undefined?.x ?? "n/a";
console.log(city); CODETOFUN NEWS
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
6 people found this page helpful