Course contentsShow
← JavaScript
Lesson 2232 of 2,72346. InternationalizationFree lesson

Practical Pluralization Patterns

Build a helper function that maps plural categories to translation strings for clean, maintainable i18n code.

Practical Pluralization Patterns

You'll learn how to build a reusable helper function that cleanly maps plural categories to translation strings, making your internationalization code maintainable and easy to update.

The Core Idea

You've learned that Intl.PluralRules gives you the correct plural category ("one", "other", "few", etc.) for any number in any locale. But what do you do with that category? The practical pattern is to create a helper function that takes a number and an object mapping categories to strings, then returns the right translation automatically.

Think of it like a vending machine: you insert a number and locale, the machine determines which button to press (the plural category), then dispenses the correct phrase.

Building the Helper

function pluralize(locale, count, translations) {
  const rules = new Intl.PluralRules(locale);
  const category = rules.select(count);
  return translations[category] || translations.other;
}

// Usage
const itemMessages = {
  one: '1 item in cart',
  other: '{count} items in cart'
};

console.log(pluralize('en', 1, itemMessages));  // "1 item in cart"
console.log(pluralize('en', 5, itemMessages));  // "{count} items in cart"

// Replace placeholder manually
const count = 5;
const message = pluralize('en', count, {
  one: '1 notification',
  other: `${count} notifications`
});
console.log(message);  // "5 notifications"

Why This Works

By separating the plural logic from your translation strings, you avoid scattered conditionals throughout your codebase. You define translations once per message, and the helper handles all locales consistently. When you need to support Polish or Arabic with their complex plural rules, you just add more keys to your translation objects—no code changes needed.

Key Takeaway: A pluralization helper that maps PluralRules categories to translation strings centralizes your i18n logic, making your codebase cleaner and easier to maintain across multiple languages.