Join strings with a delimiter only if strings are not null or empty
Let's erase those elusive null or empty elements with Array.prototype.filter() and call upon Array.prototype.join() to unite the remaining strings with your chosen delimiter:
Know your alternatives
A touch of lodash magic
If Lodash is part of your arsenal, take advantage of its simple and powerful _.filter and _.join functions:
This magic Lodash spell provides browser compatibility, including those old IE wizards.
Creating a dynamic concierge
To dynamically manage different fields, such as parts of an address, let's design a flexible function that treats arguments as an array:
Our function avoids using Array.prototype.slice.call(arguments). It's like choosing the stairs instead of the faulty elevator for optimal performance.
Incorporating concise conditional logic
Compactness can yield clarity, too. The ternary operator provides a tidy conditional check:
Brace for edge cases
jQuery's way of joining the party
When jQuery is your party planner, it makes iterating and filtering a breeze:
Difference between null and empty
Just like spotting the difference between a doorknob and a doughnut, null and empty strings can be neatly distinguished by observing its length:
Stronger types: because variety is the spice of life
The method LOVES diversity. Feed it numbers, objects, or more, and see them blend into a delicious mix of strings:
Structuring your code sandwich
Your structure is like the bread in a sandwich. Hold firm, but adapt. Consider instances like generating URLs:
Forming ways with form fields
Try to combine user input into a string, and witness our joining method carefully skip over empty fields:
Was this article helpful?