Kayote Kayote - 23 days ago 6
Javascript Question

How to simplify conditional array value addition

Here is the code:

const presets = (buildType === "___PROD___") ?
[ "react",
"es2015",
{ "modules" : false }
] : [
"react",
"es2015"
];


As can be see, the values of
react
,
es2015
are being repeated. Is it possible to not have this repetition in the ternary operator?

Best,

Answer

How about using the spread syntax?

var standardPresets = ['react','es2015'];
const presets = cond ? [ ...standardPresets , {modules: false} ] : [ ...standardPresets ];

Does you have to use a ternary if? Could you just .push into the array when that condition is met?

const standardPresets = ['react','es2015'];
if(cond){ standardPresets.push({modules: false}); }

Personally, I don't think the repetition is too awful as it is.