0 day streak
javascript / beginner
Snippet

Safely Handling Missing Values with Nullish Coalescing

JavaScript's nullish coalescing operator (??) checks if a value is null or undefined and returns a fallback value. This is especially useful in Vue computed properties when rendering optional user data without accidentally replacing valid falsy values like empty strings or zero.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
import { ref, computed } from 'vue';
const userProfile = ref({
username: 'Alex',
bio: null
});
const displayBio = computed(() => {
return userProfile.value.bio ?? 'No biography provided.';
});
vue
Breakdown
1
const userProfile = ref({
Defines a reactive object with properties that might contain null or undefined.
2
const displayBio = computed(() => {
Initializes a computed property to produce safe, presentation-ready text.
3
return userProfile.value.bio ?? 'No biography provided.';
Applies the nullish coalescing operator to provide a default string if bio is nullish.