Concatenate multiple optional items with separators

quick tip

Concatenating strings is a pretty straight forward task in JavaScript and with the introduction of template literals with string interpolation things got even simpler. Let's say that we want to concat a couple of inputs of a form that is connected to the address of the user.

const { address1, address2, address3, city } = user;

const location = `${address1}, ${address2}, ${address3}, ${city}`;

That would work perfectly fine if all the properties exist but if address3 is optional and empty on the user object it would look pretty bad.

Large Street 12, Second floor, , London

Or if address3 is undefined it would look even worse.

Large Street 12, Second floor, undefined, London

Instead of using template literals we could use a small trick putting all the properties in an array and filter out all those that are falsy (i.e. undefined and empty strings). Then just joining the remaining items together with a string of our choice, like a comma.

const { address1, address2, address3, city } = user;

const location = [address1, address2, address3, city]
  .filter(Boolean)
  .join(', ');

Now we don't need to check if each property exists and it's dynamic regardless of number of items in the array. This would then look like this:

Large Street 12, Second floor, London