Languages
[Edit]
EN

JavaScript - define array with conditional elements

0 points
Created by:
maryam
1181

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));

 

References

  1. Conditional (ternary) operator - JavaScript | MDN

Alternative titles

  1. JavaScript - define array with conditional elements using ternary operator
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join