Dave Bernhard

Web Developer

📚 Reading: Tigana by Guy Gavriel Kay

Snippet

How to conditionally add a property to an object


🔥 Bonfire|First lit on September 23, 2021
1 min read

If you have an object literal in JavaScript, and you want to add a property to it only if some condition is met, you're in luck. The neatest way is with the spread operator, introduced in ES6.

const isConditional = true;

const myObject = {
    type: 'excellent',
    size: 'enormous',
    aromas: ['jasmine', 'honeysuckle', 'puddle water'],
    ...(isConditional && { optionalProperty: true })
}

As you can see, how this actually works syntactically, is by spreading an object - { optionalProperty: true } - into our existing object literal if a certain condition is met. Handy stuff 🤚