Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

JavaScript Optional Chaining (?.) in Vue 2 and Vue 3

Use optional chaining and nullish defaults safely, choose between v-text and v-if, and handle older Vue 2 template compilers.

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.

Learn about the new optional chaining operator (?.) in JavaScript and its application in Vue.js Picture 1

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.

Learn about the new optional chaining operator (?.) in JavaScript and its application in Vue.js Picture 2

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>

Learn about the new optional chaining operator (?.) in JavaScript and its application in Vue.js Picture 3

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.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.