Combining Intl APIs for Real-World Needs
What you'll learn: How to compose multiple Intl APIs together to handle complex internationalization scenarios elegantly.
The Real Power: Composition
You've learned individual Intl APIs—NumberFormat for currency, DateTimeFormat for dates, ListFormat for natural-language lists. The real magic happens when you combine them to solve practical problems, like displaying "The items cost 12.50, and 67.24 on December 15, 2024."
Think of Intl APIs as LEGO blocks: each piece works alone, but building something meaningful requires snapping multiple pieces together in the right order.
Practical Composition Pattern
const locale = 'en-US';
// 1. Format individual prices
const prices = [45.99, 12.50, 8.75];
const currencyFormatter = new Intl.NumberFormat(locale, {
style: 'currency',
currency: 'USD'
});
const formattedPrices = prices.map(p => currencyFormatter.format(p));
// 2. Create a natural list
const listFormatter = new Intl.ListFormat(locale, {
style: 'long',
type: 'conjunction'
});
const priceList = listFormatter.format(formattedPrices);
// 3. Format the date
const date = new Date('2024-12-15');
const dateFormatter = new Intl.DateTimeFormat(locale, {
year: 'numeric',
month: 'long',
day: 'numeric'
});
// 4. Calculate and format total
const total = prices.reduce((sum, p) => sum + p, 0);
// 5. Combine everything
const message = `The items cost ${priceList}, totaling ${currencyFormatter.format(total)} on ${dateFormatter.format(date)}.`;
// "The items cost $45.99, $12.50, and $8.75, totaling $67.24 on December 15, 2024."
Each API handles its specialized task, and you orchestrate them to create cohesive, locale-aware output. Change the locale to 'de-DE', and everything adapts automatically—currency symbols, number formats, date order, and list punctuation.
Key Takeaway: Combine NumberFormat, DateTimeFormat, and ListFormat like building blocks to solve complex i18n scenarios without external libraries—each API focuses on one concern, and composition creates powerful results.