Conditional properties with object spread

1 min read

This post is part of my Today I learned series in which I share all my learnings regarding web development.

Kris Urbas shared a really neat trick to deal with conditional object properties using the object spread operator).

const shouldAddProp2 = false;
const obj = {
  prop1: 2,
  ...shouldAddProp2 && { conditionalProp2: 2 }

// it's like
// Object.assign( obj, ( shouldAddProp2 && { conditionalProp2 : 2 } ) );

console.log( obj );

Today this snippet is still hard to read for me, so I have to figure out if I should use this in the future, but it's a neat trick for sure. You can play around with it in the Babel repl.