Table of Contents
JavaScript’s optional chaining operator ?. lets you read a property when its parent may be null or undefined. In Vue, it’s useful when data has not arrived yet. Pair it with ?? for a fallback, or use v-if when the element should be absent.

Use optional chaining in JavaScript
const name = profile?.user?.name ?? 'Guest';
const firstItem = response?.items?.[0];
settings?.onLoaded?.();
The first line guards both profile and profile.user. The fallback applies only to null and undefined, so it preserves an empty string or zero. The optional call skips a missing callback, but still throws if a non-null value is present and isn’t a function. The variable itself must already be declared. See MDN’s syntax and short-circuiting examples.

Show a fallback or hide an element in Vue
In Vue 3, you can write the fallback directly in a template. This example keeps the paragraph present.
<p>{{ profile?.user?.name ?? 'Guest' }}</p>
If the paragraph should only exist when the name is present, use a condition. v-text sets the text content of an existing element. v-if controls whether the element renders.
<p v-if="profile?.user?.name != null" v-text="profile.user.name"></p>

Use a computed property on older Vue 2 projects
Vue 2.7 added ESNext template expression support for compatible build setups. If your older template compiler rejects the syntax, use a computed property with ordinary guards and reference that property from the template.
computed: {
displayName() {
const user = this.profile && this.profile.user;
return user && user.name != null ? user.name : 'Guest';
}
}
Test the production build as well as the development server if you support older browsers. For more practice with expressions and browser code, see JavaScript Fundamentals.
Reader Comments 0
Sign in with email or Google to join the discussion.