3 Ways to Initialize an Array with Conditional Elements in JavaScript

Anna Azzam
codeburst
Published in
2 min readJun 15, 2020

--

This blog will run you through 3 ways to initialize a JavaScript Array with conditional elements.

1. Create and spread an array inside the array

This method involves spreading an new array inside ofthe array with the ternary operator.

const myArray = [
'a', 'b', 'c', 'd',
... condition ? ['e'] : [],
];

When the condition is true, this will add 'e'. When it is false, it will spread an empty list[], and nothing will be added to the array.

2. Add elements conditionally and filter falsy values

Here we conditionally add elements using the ternary operator, and then filter out falsy values:

const myArray = [
'a', 'b', 'c', 'd',
condition ? 'e' : null,
].filter(Boolean);

This method will filter out all falsy values, so if your list might contain booleans, you can be more explicit and filter out only null values:

const myArray = [
'a', 'b', 'c', 'd',
condition ? 'e' : null,
].filter(x => x !== null);

3. Push to the array

The simplest and most obvious way is to define the array with all the required elements, and then conditionally call push .

const myArray = ['a', 'b', 'c', 'd'];
condition && myArray.push('e');

This will push 'e' to the end of the array when condition is true . This method only supports conditionally adding an element to the end of the array.

Hope this helped!

--

--