CodePark/ questions / The Intl APIs
START PRACTICINGPRACTICE
Frontend question · Internationalization › The Intl APIs

What is the Intl API in JavaScript, what can it format, and why use it instead of formatting by hand or with a big library?

const price = new Intl.NumberFormat("de-DE", {
  style: "currency",
  currency: "EUR",
});
price.format(1234.5); // "1.234,50 €"

new Intl.DateTimeFormat("ar-EG", { dateStyle: "long" })
  .format(new Date());

Intl is the built-in internationalization API in browsers and Node.js. It formats and compares text using the locale rules of CLDR (the Unicode Common Locale Data Repository: the shared database of how each locale writes numbers, dates and more).

The main parts:

  • Intl.NumberFormat: numbers, currencies, percentages and units ("1.234,5" in German, "1,234.5" in English).
  • Intl.DateTimeFormat: dates and times, in any time zone.
  • Intl.RelativeTimeFormat: "yesterday", "in 3 days".
  • Intl.PluralRules: which plural form a number needs.
  • Intl.ListFormat: "A, B, and C".
  • Intl.Collator: sorting and comparing strings the way a language expects.
  • Intl.Segmenter: splitting text into characters, words or sentences.
  • Intl.DisplayNames: names of languages, regions and currencies ("Germany" in any language).

Why use it:

  • Locale rules are complex. Decimal marks, digit grouping, the currency symbol's position and date order all change by locale. Hand-written code gets them wrong.
  • The data is already in the browser, so it adds 0 KB to your bundle. Libraries like Moment.js with all locales add a lot.
  • It is updated with the browser when CLDR data changes.

Tip: create a formatter once and reuse it. Creating one is slower than calling format.

  • Intl is built into browsers and Node.js and uses CLDR locale data.
  • It formats numbers, currencies, dates, relative times and lists.
  • It also handles plural rules, sorting with Collator and text splitting with Segmenter.
  • It adds nothing to the bundle, unlike big date or number libraries.
  • Create formatters once and reuse them, because creating one is slow.