Explain Codes LogoExplain Codes Logo

Implode an array with JavaScript?

javascript
join
array-manipulation
string-operations
Nikita BarsukovbyNikita Barsukov·Aug 24, 2024
TLDR

Using join() is the ticket to concatenating array elements into a single string:

const snack = ['chips', 'popcorn', 'candy']; const bingeWatchingSupply = snack.join(', '); // "chips, popcorn, candy"

Just a reminder that Array.prototype.join(delimiter) is how you transform an array into a string with a specified delimiter. Think of delimiters as peanut butter that stick array elements (or sandwich ingredients) together.🥪

Dial up the delimiter

The join() function is quite versatile and handy in handling different separation scenarios, running as smoothly as a fresh tub of butter. Let's explore some examples:

// Array of some crazy element names const elements = ['Unobtanium', 'Vibranium', 'Kryptonite']; // Space separator, because elements need space too 😉 const spaceRun = elements.join(' '); // "Unobtanium Vibranium Kryptonite" // Fancy separator for a fancy list const pipeLine = elements.join(' || '); // "Unobtanium || Vibranium || Kryptonite" // Default separator is our everyday comma const commaNdr = elements.join(); // "Unobtanium,Vibranium,Kryptonite" // Join without stuck together like clingy chips 🍿 const noSpaceForChips = elements.join(''); // "UnobtaniumVibraniumKryptonite"

Dealing with spoilt chips (aka null or undefined)

A quick note: join() handles undefined or null values by converting them into empty strings in the output.

const mixedBasket = ['apple', undefined, 'banana', null]; const list = mixedBasket.join(', '); // "apple, , banana, "

When array meets transformer: Advanced join() methods

If you need a little more pizzazz in your join operations (you fancy coder, you!) like some additional per-element processing, go for array mapping alongside join(). Here's how:

// Array of some basic numbers const numbers = [1, 2, 3, 4, 5]; // Transform each number using map() before joining const moneySequence = numbers.map(num => `$${num.toFixed(2)}`).join(', '); // "$1.00, $2.00, $3.00, $4.00, $5.00" — a wild money bag has appeared 💰!

Taking joins to new horizons

For some extra flair, consider using dynamic separators:

// Array of some boring words const words = ['Hello', 'world']; // Join them up with some firecrackers 💥 const cracklingText = words.join('!!! ') + '!!!'; // "Hello!!! world!!!"