Giving Destructured Variables Default Values

— 3 minute read


Sometimes our objects will have different properties and we want to consume them in the same way. Rather than having to handle undefineds everywhere we can give a destructured variable a fallback default value for when it's missing.

To do this we simply suffix the variable name with the default value:

const item = { id: 1, name: 'Stuart' };
const itemTwo = { id: 2, name: 'Stuart', title: 'Consultant' };

const {
id: itemId,
name,
title = 'Developer'
} = item;

console.log(itemId); // 1
console.log(name); // Stuart
console.log(title); // Developer

const {
id: itemId,
name,
title = 'Developer'
} = itemTwo;

console.log(itemId); // 2
console.log(name); // Stuart
console.log(title); // Consultant

Combining Renaming and Default Values

Before I make another blog post on the topic, I'll drop this in here! You can combine variable renaming and default values no problem at all:

const item = { id: 1, name: 'Stuart' };

const {
id: itemId,
name,
title: jobTitle = 'Developer'
} = item;

console.log(itemId); // 1
console.log(name); // Stuart
console.log(jobTitle); // Developer

Giving Destructured Variables Defaults in Vue.js Templates

If you missed my last couple of posts on Destructuring Variables in Vue.js Loops and Renaming Destructured Variables then check them out for how to use destructuring in a v-for loop. You'll be pleased to know we can also use this default value syntax inside the v-for templates!

<ul>
<li v-for="{ id, name, title: jobTitle = 'Developer' } in items" :key="itemId">
: ,
</li>
</ul>

Filed under