Emmanuel Akinfulubi

JavaScriptArray

join() vs toString() on arrays in JavaScript

Intermediate · 3 min read

Turning a list into one line of text is something you do constantly: 'Yaba, Mushin, Oshodi' for a route, a list of tags, a row in a CSV file, a breadcrumb like Home / Shop / Shoes. The method for this is join. It is simple until your list holds something awkward, like null, an empty slot or another array, and then the result can surprise you.

In this tutorial you will join a list with a separator, compare join with toString, and then join a messy array and account for every character in the result. You should know arrays and strings.

How join turns items into text

join(separator) turns each item into a string and puts the separator between them. Turning a value into a string works like String(value), with one exception: null and undefined become an empty string, not the words 'null' and 'undefined'.

JavaScript

console.log(String(42));    // '42'
console.log(String(null));  // 'null'
console.log([null].join()); // ''

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

20 join and toString

fair

Join a list with a separator. Then join one containing null, undefined, a hole and a nested array, and account for every character of the result.

Stuck? Three hints, smallest first
  1. 1. join() with no argument uses a comma, which is also what toString does.
  2. 2. null and undefined become empty strings rather than the text "null".
  3. 3. A nested array is joined too, and it always uses a comma regardless of your separator.

Step 1: join with a separator

Step 1

const stops = ['Yaba', 'Mushin', 'Oshodi'];
console.log(stops.join('-'));  // 'Yaba-Mushin-Oshodi'
console.log(stops.join(', ')); // 'Yaba, Mushin, Oshodi'
console.log(stops.join(''));   // 'YabaMushinOshodi'

The separator goes between items, never at the start or end. It can be any string, including an empty one.

Step 2: no separator, and toString

Leave the brackets empty and join uses a comma, with no space.

Step 2

const stops = ['Yaba', 'Mushin', 'Oshodi'];
console.log(stops.join());                        // 'Yaba,Mushin,Oshodi'
console.log(stops.toString());                    // 'Yaba,Mushin,Oshodi'
console.log(stops.toString() === stops.join());   // true

toString gives exactly the same thing as join(). It is what JavaScript uses when an array ends up inside a string by accident, for example 'Stops: ' + stops. If you want any other separator, call join yourself.

Step 3: the short cases

Step 3

console.log([].join('-'));    // ''
console.log(['a'].join('-')); // 'a'

An empty array gives an empty string. A single item needs no separator, so you just get that item.

Step 4: values that vanish

Now try null, undefined and a hole, an empty slot made by leaving a gap between two commas:

Step 4

const awkward = [1, null, 2, undefined, 3];
console.log(awkward.join('-'));   // '1--2--3'
console.log([1, , 3].join('-'));  // '1--3'

Count the characters in '1--2--3'. The 1, a dash, an empty string for null, a dash, the 2, a dash, an empty string for undefined, a dash, the 3. The missing values don't disappear: they leave a doubled separator behind.

On screen that looks like 'a, , b'. If you don't want the gaps, remove the missing values first with filter((v) => v != null).

Step 5: a nested array

An array inside the array is turned into text too, using its own toString, which always uses commas.

Step 5

const nested = [1, [2, 3], 4];
console.log(nested.join('-')); // '1-2,3-4'

You asked for dashes, but the inner [2, 3] became '2,3'. This catches people building CSV files: one nested value adds an extra comma, and the row now looks like it has an extra column.

Step 6: split can't always undo join

split is the opposite of join: it cuts a string into an array at each separator. It only gets your array back if no item contains the separator.

Step 6

const nested = [1, [2, 3], 4];
console.log(nested.join('-').split('-')); // [ '1', '2,3', '4' ]
console.log(['a-b', 'c'].join('-').split('-')); // [ 'a', 'b', 'c' ]

The first result is all strings, and '2,3' is stuck together. In the second, 'a-b' held the separator, so splitting cut it in two. join doesn't add quotes or escape anything, so information is lost. Choose a separator that can't appear in your data, or use JSON.stringify when you need to get the exact array back.

The full solution

The panel joins a list of stops with and without a separator, then joins arrays with null, undefined, a hole and a nested array. Press Run and match every dash and comma in the output.

The answer

const stops = ['Yaba', 'Mushin', 'Oshodi'];
const awkward = [1, null, 2, undefined, 3];
const nested = [1, [2, 3], 4];

console.log("join('-')      :", stops.join('-'));
console.log('join()         :', stops.join());
console.log('toString()     :', stops.toString(), '<- the same as join()');
console.log('--- values that vanish ---');
console.log("null/undefined :", awkward.join('-'), '<- two empty gaps');
console.log('a hole too     :', [1, , 3].join('-'));
console.log('--- nesting ---');
console.log('nested         :', nested.join('-'), '<- the inner array used a comma');
console.log('splitting back :', nested.join('-').split('-'));

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('join uses the separator you give it', stops.join('-'), 'Yaba-Mushin-Oshodi');
test('with no argument it uses a comma', stops.join(), 'Yaba,Mushin,Oshodi');
test('toString is join() by another name', stops.toString(), stops.join());
test('null and undefined become empty strings', awkward.join('-'), '1--2--3');
test('and so does a hole', [1, , 3].join('-'), '1--3');
test('a nested array is joined with a comma, not your separator', nested.join('-'), '1-2,3-4');
test('an empty array joins to an empty string', [].join('-'), '');
test('a single element needs no separator', ['a'].join('-'), 'a');
test('so join is not reversible when the data contains the separator', nested.join('-').split('-'), ['1', '2,3', '4']);

join converts each element with String() except null and undefined, which become ''. That is why a missing value shows up as a doubled separator instead of the word "null" — and why ['a', null, 'b'].join(', ') renders as "a, , b" in a user interface. Filter first if that matters.

The nesting rule catches people building CSV. An inner array is stringified with commas whatever separator you asked for, so one nested value silently corrupts a row. And since join does not quote or escape, split cannot undo it once a value contains the separator — the last assertion shows the damage.

Common mistakes

  • Expecting join() to add spaces. The default is a bare comma. Write join(', ') for a readable list.
  • Joining a list with missing values. You get doubled separators like 'a, , b'. Filter the list first.
  • Building CSV with join(','). Values that contain commas, or nested arrays, break the columns. Quote the values or use a CSV library.

Try it yourself

  1. Build the breadcrumb 'Home / Shop / Shoes' from an array.
  2. Join ['tea', null, 'milk', undefined] with ', ' so the result has no gaps.
  3. Predict the result of [[1, 2], [3, 4]].join(' | '), then check it.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.