To conditionally add a property to an object, we can make use of the && operator. In the example above, in the first property definition on obj , the first expression ( trueCondition ) is true/truthy, so the second expression is returned, and then spread into the object.
Checking array elements using the for loop First, initialize the result variable to true . Second, iterate over the elements of the numbers array and check whether each element is less than or equal zero. If it is the case, set the result variable to false and terminate the loop immediately using the break statement.
You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.
To check if all values in an array are equal:Use the Array. every() method to iterate over the array. Check if each array element is equal to the first one. The every method only returns true if the condition is met for all array elements.
You can spread an array inside of an array, in order to keep items array clean, when the condition is false
.
Here's how you can do it:
// Will result in ['foo', 'bar']
const items = [
'foo',
... true ? ['bar'] : [],
... false ? ['falsy'] : [],
]
console.log(items)
Explanations:
As you can see the ternary operator always returns an array.
If the condition is true
, then it returns ['bar']
, otherwise an empty array []
.
After that we spread out ...
the resulted array (from the ternary operation) and the array's items are pushed to the parent array.
If there aren't any array items (when the ternary check is false
), then nothing will be pushed, which is our goal.
In other answer I explained the same idea, but for objects. You can check it too here.
I'd do this
[
true && 'one',
false && 'two',
1 === 1 && 'three',
1 + 1 === 9 && 'four'
].filter(Boolean) // ['one', 'three']
Note that this will also remove falsy values, such as empty strings.
You can try with a simple if :
if(cond) {
myArr.push("bar");
}
If you really want to keep it as a one liner, you could use:
const cond = true;
const myArr = ["foo"].concat(cond ? ["bar"] : []);
You don't have so many options other than using push
:
const cond = true;
const myArr = ["foo"];
if (cond) myArr.push("bar");
Another idea is potentially adding null's and filtering them out:
const cond = true;
const myArr = ["foo", cond ? "bar" : null];
myArr = myArr.filter((item) => item !== null);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With