Coding Triumph

Helpful code snippets & tutorials

How to add an item to an array conditionally in JavaScript

Here are two little tricks you can use if you find yourself in a situation where you want to add some items to an array under a certain condition.

1. Using the spread operator:

Code:
const items = [
  'foo',
  'bar',
  ...(false ? ['baz'] : []),
  ...(true ? ['qux'] : [])
];

console.log(items);
Output:
[ 'foo', 'bar', 'qux' ]
Explanation:

The ternary operator always returns an array. So, if the condition is true, the returned array is not empty and the spread operator will push its items into the parent array. And if the condition is false, the return array is empty, and nothing will be pushed, which is our goal.

2. Using the Array.push() method:

This is another way you can use to push new items into an array conditionally. For instance:

Code:
const items = [
  'foo',
  'bar'
];

if(true){
  items.push('baz')
}

if(false){
  items.push('qux')
}

console.log(items);
Output:
[ 'foo', 'bar', 'baz' ]

Conclusion:

Which method do you prefer? Personally, I prefer the first method; it’s clean and concise.

If you like this post, please share
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments