DEV Community

Discussion on: How to conditionally build an object in ES6

Collapse
 
kepta profile image
Kushan Joshi • Edited

One of the great pitfalls of using ‘&& ||’ is that you rely on falsy values. It becomes painful when you are dealing with numbers and you have a habbit of simply using the shorthand and “0” gets treated as falsy. For example if I modify your code slightly:

function episodeParser({
    id, 
    title, 
    description = 'No summary', 
    optionalField, 
    anotherOptionalField
}) {
    return {
      ...(id && {guid: id})
      title,
      summary: description,
      ...(optionalField && {optionalField},
      ...(anotherOptionalField && {anotherOptionalField})
    }
}

let p = episodeParser({id: 0})
p.guid // undefined ! wtf?
Collapse
 
kmelve profile image
Knut Melvær

Ah, the many pitfalls of JavaScript 😅 In this case it id is always a string, but it's good that you point that gotcha out! 👌