We can use the JavaScript array filter method to filter out all the null or empty strings first before joining them together with join .
For instance, we can write:
const address = "foo";
const city = '';
const state = "bar";
const zip = '';
const text = [address, city, state, zip].filter(Boolean).join(", ");
console.log(text)
We have an array of strings with some having empty strings as their value.
So we just call filter with Boolean to filter out the ones with an empty string as their value.
And then we call join to join the non-empty strings together with a comma.
Therefore, text is 'foo, bar’ .
We can also be more precise with our filtering by writing:
const address = "foo";
const city = '';
const state = "bar";
const zip = '';
const text = [address, city, state, zip]
.filter(x => typeof x === 'string' && x.length > 0)
.join(", ");
console.log(text)
We check if x is a string and if its length is longer than 0 to make sure filter returns array of non-empty strings.
Conclusion
We can use the JavaScript array filter method to filter out all the null or empty strings first before joining them together with join .