Course contentsShow
← JavaScript
Lesson 1662 of 2,72335. Standard Library and Built-insFree lesson

Combining Plurals with Template Logic

Use PluralRules results to select the correct translation string from a set of plural forms in your application.

Combining Plurals with Template Logic

What you'll learn: How to use Intl.PluralRules results to dynamically select the correct plural translation string in your application.

Now that you can identify plural categories with PluralRules, the real power comes from acting on those results. Instead of just knowing "this is the 'few' form," you need to actually display the right translation string.

The Pattern

The typical workflow is:

  1. Get the plural category using PluralRules.select()
  2. Use that category as a key to look up the correct string
  3. Insert the number into the selected template

Here's how this looks in practice:

const pr = new Intl.PluralRules('en-US');

const templates = {
  zero: "No items",
  one: "1 item",
  other: "# items"
};

function formatItems(count) {
  const category = pr.select(count);
  const template = templates[category];
  return template.replace('#', count);
}

console.log(formatItems(0));  // "0 items" (uses 'other')
console.log(formatItems(1));  // "1 item"
console.log(formatItems(5));  // "5 items"

Multi-Language Support

This pattern scales beautifully across languages with different plural rules:

const prPolish = new Intl.PluralRules('pl');

const polishTemplates = {
  one: "# plik",
  few: "# pliki",
  many: "# plików",
  other: "# pliku"
};

function formatPolish(count) {
  const category = prPolish.select(count);
  return polishTemplates[category].replace('#', count);
}

console.log(formatPolish(1));   // "1 plik"
console.log(formatPolish(2));   // "2 pliki" (few)
console.log(formatPolish(15));  // "15 plików" (many)

Key Takeaway: Combine PluralRules.select() with an object mapping categories to template strings, then substitute the actual number to build grammatically correct phrases across any language.