The Use of Intl Keyword in JavaScript

akintoluvic

Vick Greenfields

Posted on March 16, 2023

The Use of Intl Keyword in JavaScript

Intl in Javascript is a set of tools used in enabling the design and development of an application or document that enables easy usage for target audiences in different cultures, regions or language.

According to MDN, the Intl object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting.

In this article, I will show you how to format date, time and numbers as well as other Intl built in functionalities for comparing strings without the use of any libraries or plugins.

Intl syntax

The Intl object provides access to several constructors as well as functionality common to the internationalization constructors and other language sensitive functions (MDN). Available constructors on the Intl object includes but not limited to NumberFormat, DateTimeFormat, Collator and RelativeTimeFormat.

These constructors and methods all accepts locale and options as arguments. The locale argument stands for the location to be used in carrying out an operation. Its value can be a string, undefined (when it is not provided, in which case the implementation's default value is used) or an array of locations (in which case, the first is chosen and others are fallbacks).

For the full list of supported options, consult mdn web docs. The structure for creating a new instance of the Intl object is shown below:

let myIntlFormat = new Intl.[constructor](locale, {options})

Enter fullscreen mode Exit fullscreen mode

Based on operations to be performed, either NumberFormat, DateTimeFormat, Collator or RelativeTimeFormat can be passed in as the constructor as demonstrated below:

let myIntlNumberFormat = new Intl.NumberFormat(locale, {options})

Enter fullscreen mode Exit fullscreen mode

Usage of the new instance created can then be done by appending the .format() function and passing the value to be formatted.

myIntlNumberFormat.format(23423.23)

Enter fullscreen mode Exit fullscreen mode

Formatting Currencies

The Intl.NumberFormat object can be used to format numbers to currencies based on a user's locale. This is demonstrated below:

let myNumber = 1452342.783
let formatNumberToCurrency = new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD'
})

console.log(formatNumberToCurrency.format(myNumber)) // '$1,452,342.78'

Enter fullscreen mode Exit fullscreen mode

In the example above, we are creating a new instance of the Intl.NumberFormat and passing the options of style and currencies to be formatted with. The formatter then uses that to format myNumber with the appropriate currency, decimal places and comma-separators as needed.

Number Formatting

The Intl.NumberFormat object enables the formating of numbers based on a user's location and language (without adding currencies) as shown below:

let myNumber = 1452342.783
let formatNumber = new Intl.NumberFormat('en-US')

console.log(formatNumber.format(myNumber)) // '1,452,342.78'

Enter fullscreen mode Exit fullscreen mode

Date Format

The Intl.DateTimeFormat object is useful for formating date and time based on the user's location. This requires passing in the locale code as shown below:

let myDate = new Date()
let formatDate = new Intl.DateTimeFormat('en-US')

console.log(formatDate.format(myDate)) // '23/2/2023'

Enter fullscreen mode Exit fullscreen mode

Collating and Sorting

The Intl.Collator object provides support for comparing and sorting of strings. This can be used to compare and sort strings based on the locale values provided. The Intl.Collator is used to sort an array of strings in the example below:

let myArray = ['Vick', 'Greene', 'Adele']
let myColator = new Intl.Collator('en-US')

console.log(myArray.sort(myColator.compare)) // ['Adele', 'Greene', 'Vick']

Enter fullscreen mode Exit fullscreen mode

You will notice that the syntax is different from the other ones above. Using Intl.collator requires using the .sort() function and passing the our colator object and appending it with .compare.

Relative Time Formats

Intl also support for generating relative time formats for dates thereby reducing the use of libraries for this since it is built into javascript already. Intl.RelativeTimeFormat takes locale value and a variety of options.

let relativeTimeFormatter = new Intl.RelativeTimeFormat('en', {
    numeric: 'auto'
})

console.log(relativeTimeFormatter.format(1, 'week')) // 'next week'
console.log(relativeTimeFormatter.format(-3, 'year')) // '3 years ago'
console.log(relativeTimeFormatter.format(2, 'hour')) // 'in 2 hours'

// In German
let germanTimeFormatter = new Intl.RelativeTimeFormat('es', {
    numeric: 'auto'
})
console.log(germanTimeFormatter.format(1, 'week')) // 'nächste Woche'
console.log(germanTimeFormatter.format(-3, 'year')) // 'vor 3 Jahren'
console.log(germanTimeFormatter.format(2, 'hour')) // 'in 2 Stunden'

Enter fullscreen mode Exit fullscreen mode

As you can see above, it supports both negative and positive values for dates whether in the past or in the future. And it also cancels the need for hardcoding string values, which can be quite difficult to do if you support lots of languages.

Supported units that can be passed in includes second, minute, hour, day, week, month, quater and year. You can read more about it's usage and how to extend it here and on MDN

Conclusion

Intl is a powerful tool that makes it easy to format and display data in a way that users can understand based on each user’s location. using it, empowers you to provide localized and consistent experience for your users across different countries and languages.

💖 💪 🙅 🚩
akintoluvic
Vick Greenfields

Posted on March 16, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related