Why Intl.ListFormat Fails on Empty Arrays (Fix in 14 Lines)

Опубликовано: 22 Август 2026
на канале: ZassTech Dev
0

Intl.ListFormat throws a RangeError with empty arrays — here’s why and how to fix it safely in just 14 lines of code. Learn to validate inputs, handle edge cases, and prevent runtime crashes.

▶ Final output when you run this code:
Empty array—no items to format

📋 Code explained line by line:
1. try {
→ Creates a scoped environment where exceptions can be caught by the subsequent catch block
2. const formatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });
→ Stores a reusable formatter instance in the immutable identifier formatter ready to process arrays
3. const list = [];
→ Provides the input data structure passed directly into formatter.format on the next line
4. console.log(formatter.format(list));
→ Triggers an error condition because Intl.ListFormat requires at least one item to format; the call fails and throws a RangeError
5. } catch (e) {
→ Establishes an exception handler that intercepts the RangeError produced on line three and proceeds to evaluate its type
6. if (e.name === 'RangeError') {
→ Returns true in this case because formatter.format with an empty array throws precisely a RangeError, allowing the specific handling branch to execute
7. console.log('Empty arrayno items to format');
→ Prints Empty arrayno items to format to the console as a diagnostic notice about the failure to format an empty list
8. } else {
→ Prepares to rethrow any unexpected errors using throw e so they propagate beyond this try-catch structure
9. throw e;
→ Propagates any unknown errors upward in the call stack while RangeErrors remain fully suppressed
10. }
→ Finalizes the try-catch structure and ensures no further code within this block executes before exiting
11. }
→ The program continues to the next step.