Categories
JavaScript Answers

How to Define a JavaScript Array with Conditional Elements?

Spread the love

We can use the spread operator to conditionally spread arrays into another array.

For instance, we can write:

const items = [
  'foo',
  ...true ? ['bar'] : [],
  ...false ? ['falsy'] : [],
]

console.log(items)

Then items is [“foo”, “bar”] since we have a ternary express that has false as the value of the conditional part of the ternary expression.

If it’s true , then the left array is spread into items .

Otherwise, an empty array is spread into items .

Call Array.prototype.push Conditionally

Another way to conditionally add items conditionally to a JavaScript array is to use the push method.

For instance, we can write:

const items = [
  'foo',
]

if (true) {
  items.push("bar");
}

if (false) {
  items.push("false");
}

console.log(items)

Then 'bar' is appended to items but 'false' isn’t .

This is because the first conditionally has true as the conditional and the 2nd one has false as the condition.

Therefore items is [“foo”, “bar”] again.

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 *