Emmanuel Akinfulubi

JavaScriptBasic

Pluralize a word based on count in JavaScript

Intermediate · 4 min read

Apps talk to people in sentences: "1 ticket", "3 tickets", "Ada, Bola and Chidi are going". Get it wrong and the screen says "1 tickets" or "Ada, Bola, and, Chidi", which looks careless. Choosing the singular or plural form of a word based on a count is called pluralizing.

In this tutorial you will write plural and countOf, which pick ticket or tickets from a number, and joinWords, which turns a list of names into a sentence. You need to know functions, arrow functions and arrays. Default values and || are explained below.

The two rules people get wrong

In English, only one is singular. Zero is plural: "0 tickets", not "0 ticket". So the test is "is it exactly 1?", not "is it more than 1?".

And minus one is singular too: "-1 day" in a countdown. What counts is the size of the number, ignoring its sign. Math.abs gives you that size:

JavaScript

console.log(Math.abs(-1)); // 1
console.log(Math.abs(3));  // 3

|| as a fallback

a || b gives a if a is a "truthy" value, and b otherwise. undefined, null, 0 and the empty string '' all count as falsy. That makes || handy for "use this, or else that":

JavaScript

const many = undefined;
console.log(many || 'tickets'); // tickets
console.log('buses' || 'buss'); // buses

Here is the exercise. Try it on your own first if you like, or read on and we will build it together.

148 One ticket, two tickets, and a list read aloud

fair

Write 0 tickets, 1 ticket, 2 tickets without an if at every call site, allow an irregular plural for words like bus, and join a list of names into Ada, Bola and Chidi.

Stuck? Three hints, smallest first
  1. 1. One is the only singular. Zero is plural.
  2. 2. Take the irregular plural as an optional argument and default it to the word plus s.
  3. 3. Joining: everything but the last with commas, then the word "and", then the last one.

Step 1: choose the word

Step 1

const plural = (n, one, many) => (Math.abs(n) === 1 ? one : many || one + 's');
console.log(plural(1, 'ticket'));          // ticket
console.log(plural(0, 'ticket'));          // tickets
console.log(plural(2, 'bus', 'buses'));    // buses
console.log(plural(-1, 'day'));            // day

plural takes the count, the singular word, and an optional plural word. If the size of n is exactly 1, it returns the singular. Otherwise it returns many, or, if no many was passed in, the singular with an s on the end.

The ? : is the ternary operator, a short if/else: condition ? valueIfTrue : valueIfFalse.

Step 2: why the irregular plural is an argument

Adding s works for most nouns. Try it on bus:

Step 2

const plural = (n, one, many) => (Math.abs(n) === 1 ? one : many || one + 's');
console.log(plural(2, 'bus'));          // buss
console.log(plural(2, 'bus', 'buses')); // buses

buss is wrong. Words that end in s or sh, words that end in y, and irregular words like person all break the simple rule. Rather than trying to teach the function every English spelling rule, we let the caller pass the right plural. That third argument is the escape hatch that keeps the helper simple.

Step 3: put the number in front

Most of the time you want the number and the word together:

Step 3

const plural = (n, one, many) => (Math.abs(n) === 1 ? one : many || one + 's');
const countOf = (n, one, many) => n + ' ' + plural(n, one, many);
console.log([0, 1, 2].map((n) => countOf(n, 'ticket')).join(' / ')); // 0 tickets / 1 ticket / 2 tickets
console.log(countOf(4, 'bus', 'buses'));                            // 4 buses
console.log(countOf(-2, 'day'));                                     // -2 days

Now every place in the app that shows a count calls countOf instead of writing its own if.

Step 4: join a list the way people say it

For a list of names we want "Ada, Bola and Chidi": commas between all but the last two, then the word "and". Start with the easy cases:

Step 4

function joinWords(items, conjunction = 'and') {
  if (items.length === 0) return '';
  if (items.length === 1) return items[0];
  return items.slice(0, -1).join(', ') + ' ' + conjunction + ' ' + items[items.length - 1];
}
console.log(joinWords(['Ada', 'Bola', 'Chidi'])); // Ada, Bola and Chidi
console.log(joinWords(['Ada', 'Bola']));          // Ada and Bola
console.log(joinWords(['Ada']));                  // Ada
console.log(joinWords([]));                       // (an empty string)

slice(0, -1) takes every item except the last one. A negative number in slice counts from the end. join(', ') puts commas between those, and then we add the conjunction and the last item.

conjunction = 'and' is a default parameter: if the caller leaves it out, it is 'and'. Sometimes you need "or" instead:

JavaScript

function joinWords(items, conjunction = 'and') {
  if (items.length === 0) return '';
  if (items.length === 1) return items[0];
  return items.slice(0, -1).join(', ') + ' ' + conjunction + ' ' + items[items.length - 1];
}
console.log(joinWords(['cash', 'transfer', 'card'], 'or')); // cash, transfer or card

The two early returns matter. Without them, an empty list would produce ' and undefined', and a single name would come out as ' and Ada'.

Whether there should be a comma before "and" ("Ada, Bola, and Chidi") is a matter of house style, not correctness. This version leaves it out, as British and Nigerian English usually do.

Step 5: build a sentence

Step 5

const plural = (n, one, many) => (Math.abs(n) === 1 ? one : many || one + 's');
const countOf = (n, one, many) => n + ' ' + plural(n, one, many);
function joinWords(items, conjunction = 'and') {
  if (items.length === 0) return '';
  if (items.length === 1) return items[0];
  return items.slice(0, -1).join(', ') + ' ' + conjunction + ' ' + items[items.length - 1];
}
const riders = ['Ada', 'Bola', 'Chidi'];
const sentence = countOf(3, 'ticket') + ' for ' + joinWords(riders) + ', on ' + countOf(2, 'bus', 'buses') + '.';
console.log(sentence); // 3 tickets for Ada, Bola and Chidi, on 2 buses.

The full solution

The answer panel has plural, countOf and joinWords, and builds the sentence above. The checks cover zero, one and two, the irregular plural, minus one, lists of every length and the or conjunction. Press Run to see the output.

The answer

const plural = (n, one, many) => (Math.abs(n) === 1 ? one : many || one + 's');
const countOf = (n, one, many) => n + ' ' + plural(n, one, many);

function joinWords(items, conjunction = 'and') {
  if (items.length === 0) return '';
  if (items.length === 1) return items[0];
  return items.slice(0, -1).join(', ') + ' ' + conjunction + ' ' + items[items.length - 1];
}

const riders = ['Ada', 'Bola', 'Chidi'];
const sentence = countOf(3, 'ticket') + ' for ' + joinWords(riders) + ', on ' + countOf(2, 'bus', 'buses') + '.';
console.log(sentence);
console.log([0, 1, 2].map((n) => countOf(n, 'ticket')).join(' / '));

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('zero is plural, one is not, two is', [0, 1, 2].map((n) => countOf(n, 'ticket')), ['0 tickets', '1 ticket', '2 tickets']);
test('an irregular plural is passed in', [countOf(1, 'bus', 'buses'), countOf(4, 'bus', 'buses')], ['1 bus', '4 buses']);
test('and the default would have been wrong for it', plural(2, 'bus'), 'buss');
test('minus one is singular too', [countOf(-1, 'day'), countOf(-2, 'day')], ['-1 day', '-2 days']);
test('a list of three reads properly, with no comma before the and', joinWords(riders), 'Ada, Bola and Chidi');
test('two names take no comma at all, one takes no conjunction', [joinWords(['Ada', 'Bola']), joinWords(['Ada'])], ['Ada and Bola', 'Ada']);
test('an empty list is an empty string, not the word and', joinWords([]), '');
test('the conjunction is a parameter, because sometimes it is or', joinWords(['cash', 'transfer', 'card'], 'or'), 'cash, transfer or card');
test('and the two together make a sentence', sentence, '3 tickets for Ada, Bola and Chidi, on 2 buses.');

Two rules people get wrong. Zero is plural in English — 0 tickets, not 0 ticket — so the test is n === 1 and not n > 1. And it is the magnitude that decides, so -1 is singular; Math.abs costs nothing and covers refunds and countdowns.

many || one + 's' is a deliberate compromise, and the third assertion is honest about it: the default turns bus into buss. Adding s covers most English nouns and fails on sibilants, words ending in y, and every irregular, so the parameter is not optional in practice — it is the escape hatch that keeps the helper usable. If a screen has more than a handful of these, the real answer is a message catalogue with plural forms, because languages like Arabic and Polish have three to six plural categories and no amount of n === 1 will reach them.

The list join has one interesting case: two items take no comma, which a naive items.join(', ').replace(/,([^,]*)$/, ' and$1') also gets right but by accident. Slicing off the last item states the rule directly. Whether a comma belongs before the and is a house style question, not a correctness one — this version omits it, which is the British and Nigerian convention.

Common mistakes

  • Testing n > 1. That makes zero singular: "0 ticket". Test Math.abs(n) === 1.
  • Trusting + 's' for every word. You get buss and persons. Pass the plural in.
  • Joining every item with ', ' and forgetting short lists. Handle zero and one item before the general case.

Try it yourself

  1. Use countOf to print "1 person" and "5 people".
  2. Add a third style to joinWords that puts a comma before "and" when there are three or more items.
  3. Write summary(names) that returns "No riders", "Ada is riding" or "Ada and Bola are riding", choosing "is" or "are" from the count.

Keep practising

Newsletter

New writing, when it lands.

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