Join an array into a comma-separated string in JavaScript
Beginner · 3 min read
You have a list of items in an array and you want to show it as text: 'rice, beans, yam' in a shopping summary, a comma-separated line for a CSV file, or a sentence like "rice, beans and yam". The method for this is join.
In this tutorial you will join an array with different separators, find out what join does with null, undefined and nested arrays, and then write a small function that builds a proper English list with "and" before the last item. You should know what an array is.
What join does
array.join(separator) turns every item into text and glues them together, putting the separator between each pair. It returns a new string and leaves the array alone.
console.log(['a', 'b', 'c'].join(' | ')); // 'a | b | c'
The separator only goes between items, never before the first or after the last.
Turning values into text
join has to turn each item into a string first. Numbers become their digits, so 3 becomes '3'. Two values are treated specially: null and undefined become an empty string, not the words 'null' and 'undefined'. You will see why that matters in Step 4.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
24 Join an array back into a string
easyTurn ['rice', 'beans', 'yam'] into 'rice, beans, yam'. Then find out what join does with null and with a nested array.
Stuck? Three hints, smallest first
- 1. The default separator is a comma with no space, which is rarely what you want.
- 2.
nullandundefinedbecome empty strings, not the words. - 3. A sentence list needs "and" before the last item, so
joinalone will not do it.
Step 1: join with a comma and a space
const items = ['rice', 'beans', 'yam'];
console.log(items.join(', ')); // 'rice, beans, yam'
That is the result the exercise asks for.
Step 2: the default separator
If you leave the brackets empty, join uses a comma with no space:
const items = ['rice', 'beans', 'yam'];
console.log(items.join()); // 'rice,beans,yam'
console.log(items.join('')); // 'ricebeansyam'
The default is fine for a CSV line but looks cramped to a reader. An empty string glues the items with nothing between them.
Step 3: one item, or none
console.log(['rice'].join(', ')); // 'rice'
console.log([].join(', ')); // '' (an empty string)
One item needs no separator, so you get the item itself. An empty array gives an empty string. Neither case throws an error, so you don't need special code for them.
Step 4: null and undefined leave gaps
console.log(['a', null, undefined, 'b'].join('-')); // 'a---b'
console.log(String(null)); // 'null'
Four items means three dashes. The two missing values became empty strings, so they show up only as doubled separators. That is easy to miss in output and impossible to search for. Notice that String(null) gives the word 'null': join really does treat these two values differently.
If missing values should be skipped, filter them out first:
const list = ['a', null, undefined, 'b'];
console.log(list.filter((x) => x != null).join('-')); // 'a-b'
x != null, with one =, is true for everything except null and undefined.
Step 5: numbers and nested arrays
console.log([1, 2, 3].join('+')); // '1+2+3'
console.log([['a', 'b'], 'c'].join('-')); // 'a,b-c'
Numbers are converted for you. The nested array is the odd one: it is turned into text on its own, and an array turned into text always uses commas, whatever separator you asked for. Flatten the array with flat() first if it might contain arrays.
Step 6: a list that reads like English
People write "rice, beans and yam", with "and" before the last item. join uses the same separator everywhere, so it can't do that alone. Split the job in two: join every item except the last with commas, then add " and " and the last item.
const sentence = (list) =>
list.length < 2 ? list.join('') : list.slice(0, -1).join(', ') + ' and ' + list.at(-1);
console.log(sentence(['rice', 'beans', 'yam'])); // 'rice, beans and yam'
console.log(sentence(['rice', 'beans'])); // 'rice and beans'
console.log(sentence(['rice'])); // 'rice'
list.slice(0, -1) is every item except the last, and list.at(-1) is the last item. A list with fewer than two items has nothing to put "and" between, so it is just joined as it is.
The full solution
Here is the complete answer: the different separators, the null gap, the nested array and the sentence function. Press Run to see each result, then read the checks.
const items = ['rice', 'beans', 'yam'];
// A readable list needs the last separator to be different.
const sentence = (list) =>
list.length < 2 ? list.join('') : list.slice(0, -1).join(', ') + ' and ' + list.at(-1);
console.log("join(', ') :", items.join(', '));
console.log('join() :', items.join(), '<- comma, no space');
console.log('sentence :', sentence(items));
console.log("[null, 'b'].join('-') :", ['a', null, undefined, 'b'].join('-'), '<- holes, not the words');
Output
11 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 11 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('join with a comma and a space', items.join(', '), 'rice, beans, yam');
test('the default separator is a bare comma', items.join(), 'rice,beans,yam');
test('an empty separator glues them together', items.join(''), 'ricebeansyam');
test('one item needs no separator', ['rice'].join(', '), 'rice');
test('an empty array joins to an empty string', [].join(', '), '');
test('null and undefined become EMPTY, not the words', ['a', null, undefined, 'b'].join('-'), 'a---b');
test('even though String(null) is the word', String(null), 'null');
test('numbers are converted for you', [1, 2, 3].join('+'), '1+2+3');
test('a nested array is joined too, with commas', [['a', 'b'], 'c'].join('-'), 'a,b-c');
test('a readable list needs more than join', sentence(items), 'rice, beans and yam');
test('and it still handles a single item', sentence(['rice']), 'rice');
The null behaviour is the one that produces a puzzling gap in output. ['a', null, 'b'].join('-') is 'a--b', so a missing value shows up as a doubled separator rather than as anything you can search for. Filter first: list.filter((x) => x != null).join('-').
The nested-array case is String(['a','b']) at work — an array converts to its own comma-joined form regardless of the separator you asked for. Flatten before joining if the input might be ragged.
Common mistakes
- Relying on the default separator.
join()gives'rice,beans,yam'with no spaces. Pass', 'when people will read it. - Not noticing missing values.
nullandundefinedturn into empty strings and leave doubled separators. Filter them out first. - Joining a list of arrays. Inner arrays always use commas. Call
flat()beforejoin.
Try it yourself
- Change
sentenceso it adds a comma before "and" ('rice, beans, and yam'). - Join
[2025, 4, 9]into'2025/4/9'. - Join
['a', ['b', 'c'], 'd']with' | 'so the result is'a | b | c | d'.