Join strings with a comma only if strings are not null or empty

Today, we’ll show you how to join strings with a comma only if strings are not null or empty.

Here, we will use the join Array method with comma delimiter to concat the strings. But we will also add one more check to filter the empty or null records.

In this article, we will try to combine the following strings with a comma delimiter.

Join strings using a comma

Let’s combine the above strings using the join() method and check the output log.

You may have noticed that we have multiple commas next to each other when values are empty or null. So use the following code to avoid it.

In the above code, we have used the .filter(Boolean) (which is the same as .filter(x => x)) to remove all falsy values (null, undefined, empty strings etc).

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *