Enjoy 20% off all plans by following us on social media. Check out other promotions!
Quiz Questions

What is the `Intl` namespace object for?

Topics
JAVASCRIPTINTERNATIONALIZATION
Edit on GitHub

TL;DR

The Intl namespace object in JavaScript is used for internationalization purposes. It provides language-sensitive string comparison, number formatting, and date and time formatting. For example, you can use Intl.DateTimeFormat to format dates according to a specific locale:

const date = new Date();
const formatter = new Intl.DateTimeFormat('en-US');
console.log(formatter.format(date)); // Outputs date in 'MM/DD/YYYY' format

What is the Intl namespace object for?

The Intl namespace object in JavaScript is a part of the ECMAScript Internationalization API, which provides language-sensitive string comparison, number formatting, and date and time formatting. This is particularly useful for applications that need to support multiple languages and regions.

Language-sensitive string comparison

The Intl.Collator object is used for comparing strings in a locale-aware manner. This is useful for sorting strings in a way that is consistent with the conventions of a particular language.

const collator = new Intl.Collator('de-DE');
console.log(collator.compare('ä', 'z')); // Outputs a negative number because 'ä' comes before 'z' in German

Number formatting

The Intl.NumberFormat object is used for formatting numbers according to the conventions of a specific locale. This includes formatting for currency, percentages, and plain numbers.

const number = 1234567.89;
const formatter = new Intl.NumberFormat('de-DE', {
style: 'currency',
currency: 'EUR',
});
console.log(formatter.format(number)); // Outputs '1.234.567,89 €'

Date and time formatting

The Intl.DateTimeFormat object is used for formatting dates and times according to the conventions of a specific locale.

const date = new Date();
const formatter = new Intl.DateTimeFormat('en-GB', {
year: 'numeric',
month: 'long',
day: 'numeric',
});
console.log(formatter.format(date)); // Outputs date in 'DD Month YYYY' format

Plural rules

The Intl.PluralRules object is used to get the plural form of a number in a specific locale. This is useful for correctly pluralizing words in different languages.

const pluralRules = new Intl.PluralRules('en-US');
console.log(pluralRules.select(1)); // Outputs 'one'
console.log(pluralRules.select(2)); // Outputs 'other'

Further reading

Edit on GitHub