Formatting Arrays as Readable Lists in JavaScript

Formatting an array as a readable list in JavaScript can be done easily using the following method:

const authors = ["Ronald L. Rivest", "Adi Shamir", "Len Adleman"];

const formatter = new Intl.ListFormat("en", {
  style: "long",
  type: "conjunction",
});

console.log(formatter.format(authors));

// expected output:
// Ronald L. Rivest, Adi Shamir, and Len Adleman

The Intl.ListFormat object allows for language-sensitive list formatting. By specifying a different language code, such as "pt-br" for Brazilian Portuguese, the output can be customized accordingly:

// Ronald L. Rivest, Adi Shamir e Len Adleman

The Oxford comma

The usage of the Oxford comma in list formatting can vary based on the language. In Portuguese, for example, the output does not include an Oxford comma. Some English locales include it, while others do not. For instance, locales like "eu-AU" and "en-GB" do not include the Oxford comma, whereas "en" and "en-US" do.

The reason for this discrepancy across locales is unclear, and I couldn't find a definitive answer during my research.

Browser support

Most modern browsers support the Intl.ListFormat object by default, with the exception of Safari and IE. If you require support for these browsers, a polyfill is available on GitHub.

To learn more about the Intl.ListFormat object, you can visit the MDN documentation here ↗