Skip to content
loading...

re: How to conditionally build an object in ES6 VIEW POST

FULL DISCUSSION
 

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?
 

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! 👌

code of conduct - report abuse