1. International List Format
Let’s say your goal is to format array items in a sentence to render it in HTML etc.
For Example:
const thingsILikeToEat = ['Pizza', 'Burger', 'Noodles', 'Tacos'];
You might be tempted to do:
// ❌ Don't
thingsILikeToEat.slice(0, -1).join(', ').concat(', and', thingsILikeToEat.slice(-1));
// Output: Pizza, Burger, Noodles, and Tacos
Instead of writing a list formatting function or doing split/join/concat, consider using Intl.ListFormat
.
// ✅ Do
new Intl.ListFormat('en').format(thingsILikeToEat);
// Output: Pizza, Burger, Noodles, and Tacos
You could also do ‘or’ instead of ‘and’, change language ‘en’ to your prefered language etc.
const formatList = new Intl.ListFormat('en', { style: 'short', type: 'disjunction' });
formatList.format(thingsILikeToEat);
// Output: Pizza, Burger, Noodles, or Tacos
2. Destructuring Assignmet
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
For Example:
const [favourite, best, ...rest] = ['Pizza', 'Burger', 'Noodles', 'Tacos'];
// Output:
// console.log(favourite);
// Pizza
// -------
// console.log(best);
// Burger
// -------
// console.log(rest);
// ['Noodles', 'Tacos']
This method can be used for more complex scenarios also or when you’re using Promise.all
etc.
const [pizza, burger] = [
{ name: 'Pizza', size: 'Large' },
{ name: 'Burger', size: 'small' },
];
// Output:
// console.log(pizza);
// { name: 'Pizza', size: 'Large' }
// -------
// console.log(burger);
// { name: 'Burger', size: 'small' }
// -------
3. International Number Format
The Intl.NumberFormat
object enables language-sensitive number formatting.
const number = 123456.789;
console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number));
// Output: "123.456,79 €"
// the Japanese yen doesn't use a minor unit
console.log(new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(number));
// Output: "¥123,457"
// limit to three significant digits
console.log(new Intl.NumberFormat('en-IN', { maximumSignificantDigits: 3 }).format(number));
// Output: "1,23,000"
You could also use it for basic number formating
const number = 3500;
console.log(new Intl.NumberFormat().format(number));
// → '3,500' if in US English locale
The full options list can be found here
Hope you found this article on Javascript Tips Series helpful. ❤️