Categories
JavaScript Answers

How to define an array with conditional elements with JavaScript?

Spread the love

To define an array with conditional elements with JavaScript, we use the ternary operator.

For instance, we write

const items = ["foo", ...(true ? ["bar"] : []), ...(false ? ["falsy"] : [])];

console.log(items);

to spread the entries in ["bar"] since the condition is true.

And we spread the empty array into the array since false is before the 2nd ternary operator.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *