The JavaScript array.join() method
The join() method turns an array into a string, placing a separator of your choice between elements. ["a", "b", "c"].join("-") gives "a-b-c". With no argument it uses a comma. It's the natural counterpart to split(), which goes the other way, from string back to array.
Overview
join() flattens an array into a single string. You give it the glue — the separator to put between elements — and it stitches everything together. join(", ") for a readable list, join("") to mash elements together with nothing between, join(" / ") for a breadcrumb. Pass no argument and it defaults to a comma.
It's the mirror image of split(): split breaks a string into an array, join glues an array into a string. The two together are a common idiom for transforming text — split on spaces, map over the words, join back up. The original array isn't changed; you just get a string out.
One quirk worth knowing: null and undefined elements become empty strings in the output, so [1, null, 3].join("-") gives "1--3". Everything else is converted with its normal string form. If you just want the default comma-separated version, toString() does the same thing, but join() is clearer because it shows the separator.
Syntax
const str = array.join() // comma-separated by default
const str = array.join(separator) // your separator between elements
Parameters
The array.join() method accepts the following parameters.
| Parameter | Description |
|---|---|
separator |
Optional. The string placed between elements. Defaults to a comma (","). Use "" for no separator. |
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const tags = ['html', 'css', 'js'];
document.getElementById('out').textContent =
tags.join(', ') + '\n' +
tags.join(' > ') + '\n' +
tags.join('');
// html, css, js / html > css > js / htmlcssjs
</script>
Best practices
- Pass an explicit separator —
join(", ")orjoin("")— so the output is obvious from the code. - Pair it with split() to round-trip between strings and arrays.
- Remember
nullandundefinedbecome empty strings, which can leave doubled separators. - Build HTML or CSV lists by mapping first, then joining —
items.map(...).join("").
Frequently asked questions
How do I turn an array into a string in JavaScript?
arr.join(separator), e.g. arr.join(", "). With no argument it joins with commas.What is the difference between join() and split()?
join() combines an array into a string; split() breaks a string into an array. They're opposites.How do I join an array with no separator?
arr.join("").What happens to null or undefined when joining?
[1, null, 2].join("-") is "1--2".