Conditional properties with object spread

Published at
Updated at
Reading time
1 min

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 (currently at proposal stage 3).

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.

Related Topics

See null comment.