DEV Community

Cover image for Elegant JavaScript Code - Combining Two Strings
Carl Saunders
Carl Saunders

Posted on

Elegant JavaScript Code - Combining Two Strings

Today I've implemented a function (combineLabels) to combine two string together, here are the requirements for said function:-

  • Return both strings combined using the supplied separator
  • Return the first string if the second string is falsy
  • Return the second string if the first string is falsy
  • Return an empty string is both strings are falsy

Now, I could of implemented this using multiple if statements, but the following approach is more elegant and less code and handles all of the above scenarios.

const combineLabels = (label1, label2, separator = ' - ') => {
  return [ label1, label2 ].filter(Boolean).join(separator);
}
Enter fullscreen mode Exit fullscreen mode

Let me explain what is going on with the code. Firstly I'm creating an array of the two labels passed into the function. Then comes the magic, by performing the .filter(Boolean), this excludes all the items that evaluate to a falsy value ('', undefined, null, etc) from the array. Once the items are excluded the join method then joins the strings together using the supplied separator. The separator is ignore when there are no strings in the array or when only one is present.

The listing below shows examples of calling the function, along with the return values.

combineLabels('Label 1', 'Label 2'); // returns 'Label 1 - Label 2'
combineLabels('Label 1', 'Label 2', ','); // returns 'Label 1,Label 2'
combineLabels('Label 1', undefined); // returns 'Label 1'
combineLabels('Label 1', null); // returns 'Label 1'
combineLabels('Label 1', ''); // returns 'Label 1'
combineLabels(undefined, 'Label 2'); // returns 'Label 2'
combineLabels(null, 'Label 2'); // returns 'Label 2'
combineLabels('', 'Label 2'); // returns 'Label 2'
combineLabels('', ''); // returns ''
combineLabels(undefined, undefined); // returns ''
combineLabels(null, null); // returns ''
combineLabels(undefined, null); // returns ''
combineLabels(undefined, ''); // returns ''
combineLabels(null, undefined); // returns ''
combineLabels(null, ''); // returns ''

Enter fullscreen mode Exit fullscreen mode

So, what elegant code have you written today?

Top comments (0)