Get the User's Locale in the Browser using JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 6, 2024
2 min

banner

# Get the User's Locale in the Browser using JavaScript

To get the user's locale in the browser, access the first element of the languages property on the navigator object, e.g. navigator.languages[0].

The property returns an array of strings that represent the user's preferred languages.

index.js
const userLocale = navigator.languages && navigator.languages.length ? navigator.languages[0] : navigator.language; console.log(userLocale); // ๐Ÿ‘‰๏ธ "en-US" // ๐Ÿ‘‡๏ธ ["en-US", "en", "de"] console.log(navigator.languages);

get user locale in browser

The code for this article is available on GitHub

We used the navigator.languages property to get an array containing the user's preferred languages.

The languages are described using BCP 47 tags (tags for identifying languages).

The elements in the array are ordered by preference, with the most preferred language first.

Internet Explorer does not support the navigator.languages property, so we used a ternary operator to conditionally check if the property is available in the given browser.

The ternary operator is very similar to an if/else statement.

If the expression to the left of the question mark returns a truthy value, the value to the left of the colon is returned, otherwise, the value to the right is returned.

If the navigator.languages property is not supported in the browser, we fall back to the navigator.language property.

The property returns a string that represents the user's preferred language. This is usually the language of the user's browser UI.

index.js
// ๐Ÿ‘‡๏ธ ["en-US", "en", "de"] console.log(navigator.languages); // "en-US" console.log(navigator.language);

accessing language and languages properties

The code for this article is available on GitHub

Examples of the value of the languages property include - en, en-US, fr, fr-FR, etc.

If the navigator.languages property is supported in the browser, the first element in the array of languages will most commonly be the value stored by the navigator.language property.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev