EN
JavaScript - define array with conditional elements
0
points
In this article, we would like to show you how to define array with conditional elements in JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
const condition = true;
const array = [
'element-1',
...(condition ? ['true-case'] : ['false-case']), // conditional element
];
console.log(JSON.stringify(array));
Practical example
In this example, we create an array with two conditional elements. The elements appear depending on the conditions, so the array can contain from 1 up to 3 elements.
// ONLINE-RUNNER:browser;
const condition1 = true;
const condition2 = false;
const array = [
'element-1',
...(condition1 ? ['element-2'] : []), // conditional element
...(condition2 ? ['element-3'] : []), // conditional element
];
console.log(JSON.stringify(array));