The question is published on by Tutorial Guruji team.
In order to determine the current locale I found different approaches:
- Being in the browser, most people suggest looking at the HTTP headers (
Accept-Language
) - Some people suggest consulting
navigator.language
- Being in the backend (Node.js) and apart of HTTP, it is suggested to consult the (system dependent)
process.env
On the other side, the ECMAScript Internationalization API defines the locales
argument to each of the Intl
constructors as optional:
If the
locales
argument is not provided or is undefined, the runtime’s default locale is used.
So, it seems as if there should be a browser-independent and OS independent way to get “the runtime’s default locale”.
Is there a more straight forward way to get the runtime’s default locale than
new Intl.NumberFormat().resolvedOptions().locale
?
The question How/Where does JavaScript detect the default locale? is different as it asks for the implementation of detecting the default locale (in a browser host). In contrast to that, my question is not about implementation but about the existence of a standard API.
Answer
I’m not aware of a more straight-forward approach, but as you have already pointed out,
new Intl.NumberFormat().resolvedOptions().locale
is a solutionDefaultLocale
is an abstract operation, which might or might not be implemented in the future.
Hence, I would argue for polyfilling this function
as:
if (typeof DefaultLocale === "undefined") { function DefaultLocale() { return new Intl.NumberFormat().resolvedOptions().locale; } }
So, your code will reasonably assume the existence and call this function
. In some point in the future, when this function
is implemented in a standard manner, you will be able to clean up by removing the chunk from above.