Skip to content
jshacks.dev
Fundamentals

JavaScript Array join Explained With Clear Examples

Array join() turns an array into one string with a separator. See how it treats null, undefined, nested arrays and sparse slots, with exact output.

6 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, npm and TypeScript logos.

join() looks too simple to go wrong, and then a list containing null produces "a,,b" instead of an error, a nested array flattens into the output without being asked, and a missing separator argument inserts commas that break a CSV column. Each of those is documented behavior, and each has cost someone an afternoon. This post walks through what join() does with every kind of element, how it differs from toString() and template literals, and when building a string by hand is the better choice. Examples run on Node.js 24. If you need to build the array first, [the post on map()](/library/javascript-array-map) pairs well with this one.

What join() takes and returns

The signature is array.join(separator). It converts every element to a string, places the separator between neighbors, and returns one string. The array is not modified.

CaseResult
No argumentElements joined with ","
Separator ""Elements joined with nothing between them
Empty array""
One elementThat element as a string, with no separator
JavaScript
const parts = ["2026", "05", "06"];

console.log(parts.join("-"));
console.log(parts.join(""));
console.log(parts.join());
console.log([].join("-") === "");
Text
2026-05-06
20260506
2026,05,06
true

The default separator is a comma with no space, which surprises people who expect ", ". If you want readable output, pass the separator you mean, and do not rely on the default.

How each element is converted

Every element goes through string conversion, with one exception: null and undefined become the empty string, not the words "null" and "undefined".

JavaScript
const mixed = [1, null, "x", undefined, true, 2.50];

console.log(mixed.join("|"));
console.log(String(null), String(undefined));
Text
1||x||true|2.5
null undefined

The two empty slots appear as nothing between the pipes. That is different from String(null), which gives the text "null", and different from a template literal, which also gives "null". If a report column must show a placeholder for missing data, map first and join second:

JavaScript
const cells = ["id-7", null, "open"];
console.log(cells.map((c) => c ?? "n/a").join(" | "));
Text
id-7 | n/a | open

Numbers use their normal string form, so 2.50 prints as 2.5. Formatting decimals is a separate step, and toFixed() before join() is the usual answer.

Nested arrays and objects

An element that is itself an array is converted by calling its own toString(), which is join() with a comma. So nesting flattens one level of structure into the text, and deeper arrays flatten all the way down.

JavaScript
const grid = [[1, 2], [3, [4, 5]]];

console.log(grid.join(";"));
console.log(grid.join(";").split(";").length);
Text
1,2;3,4,5
2

The inner arrays came out with commas, which is why the separator you chose is not the only delimiter in the result. If you later split on the outer separator you get two items, and each still contains commas. Flatten explicitly with flat() when you want one delimiter, or serialize with JSON.stringify() when structure must survive.

Plain objects convert to "[object Object]", which is almost never what you wanted.

JavaScript
const rows = [{ id: 1 }, { id: 2 }];

console.log(rows.join(", "));
console.log(rows.map((r) => r.id).join(", "));
Text
[object Object], [object Object]
1, 2

Pull out the field you need before joining. A class with its own toString() method will use it, so defining one is another route.

Cyclic references and sparse arrays

join() guards against infinite recursion. If an array contains itself, the inner reference becomes an empty string instead of looping.

JavaScript
const loop = [1, 2];
loop.push(loop);

console.log(loop.join("-"));
Text
1-2-

The third element is the array itself, which is detected as already being joined and rendered as nothing. You get the trailing separator but no error and no stack overflow.

Sparse arrays behave like undefined here: a hole contributes an empty string, so the separators still appear.

JavaScript
const sparse = [1, , 3];
console.log(sparse.join("+"));
console.log(new Array(3).join("ab"));
Text
1++3
abab

The second line is a classic trick. An array of three holes joins to two copies of the separator, which is how people used to repeat a string before repeat() existed. Use "ab".repeat(2) in new code, because it says what it means.

join() versus toString() and template literals

Array.prototype.toString() simply calls join() with no argument, so [1, 2].toString() is "1,2". A template literal such as ${list} goes through the same conversion, which means an array interpolated into text prints with commas and no spaces.

JavaScript
const tags = ["js", "node"];

console.log(`${tags}`);
console.log(tags.toString() === tags.join(","));
console.log("Tags: " + tags);
Text
js,node
true
Tags: js,node

Implicit conversion hides intent and locks you to the comma default. We call join() explicitly every time, even when the default would do, so a reader can see the delimiter is deliberate.

Joining for humans and for machines

For text that people read, a plain join(", ") ignores grammar. Intl.ListFormat produces locale-correct lists with the right conjunction.

JavaScript
const names = ["Ana", "Ben", "Cho"];

const list = new Intl.ListFormat("en", { style: "long", type: "conjunction" });
console.log(list.format(names));
console.log(names.join(", "));
Text
Ana, Ben, and Cho
Ana, Ben, Cho

Use Intl.ListFormat for sentences shown to users and join() for identifiers, paths, class names and log lines. For CSV or query strings, joining by hand breaks the moment a value contains the separator, so use a proper encoder: URLSearchParams for queries, and a quoting rule for CSV fields.

A path is a good example of a case where the separator is not the whole story. ["a", "b"].join("/") is fine for URL segments, but on the file system use path.join() from node:path, which normalizes duplicate slashes and handles the platform separator.

A failure we keep seeing: joining user input

The most common real bug with join() is assembling a delimited string from values that may contain the delimiter. A tag list joined with commas works until someone types a tag containing a comma, and then the string cannot be split back into the original items, because the information about where one item ended is gone. The same happens with pipes in log fields and semicolons in cookie-style values.

JavaScript
const tags = ["css", "a,b", "html"];
const stored = tags.join(",");

console.log(stored);
console.log(stored.split(",").length);
Text
css,a,b,html
4

Three tags went in and four came out. The fix is to pick a format that carries its own structure. JSON.stringify(tags) round-trips any content, and a database column of type array or a join table avoids the problem entirely. Choose a plain delimiter only when you control every value, such as a fixed set of enum names, and say so in a comment near the code so the next editor does not widen the input.

Joining with a computed separator

The separator can be any string, including one built from data, which is handy for formatted output. A multi-character separator works the same way as a single character, and an empty string is a valid choice when you want concatenation without gaps. Newlines are the other everyday case: lines.join("\n") produces a block of text with no trailing newline, so add one yourself if the file format expects it.

Where join() stops being the right tool

join() builds one string in memory, so it is the wrong choice for very large outputs that you could stream. It also does no escaping, so never use it to assemble HTML, SQL or shell commands from untrusted values. And it cannot distinguish a missing value from an empty one, because both print as nothing. When that distinction matters, map to an explicit marker first, as shown above.

For splitting a string back apart, see [the post on split()](/library/javascript-string-split), which has its own edge cases with empty strings and limits. The behavior of join() is defined in the ECMAScript specification under Array.prototype.join, and MDN documents it on the Array.prototype.join page.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.