Method 1: Ternary Operators and Filter Method
This method takes advantage of JavaScript's ternary operators and the filter method of arrays. An element is added to the array conditionally using a ternary operator and the resulting array is filtered to exclude any null values.
Here's a sample code snippet:
Method 2: Spread Syntax
This approach uses JavaScript's spread syntax (...
).
It's more concise and doesn't require additional filtering.
If the condition is true
, an array item gets included.
If the condition is false
, an empty array gets spread, which effectively includes no extra elements.
Here's a sample code snippet: