Published at
Updated at
Reading time
1min
This post is part of my Today I learned series in which I share all my web development learnings.

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.

If you enjoyed this article...

Join 5.2k readers and learn something new every week with Web Weekly.

Web Weekly — Your friendly Web Dev newsletter
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles