Detecting the current culture in javascript can be really useful in many cases, for example when you have a dropdown with the list of languages and you want the user’s preferred one already selected.

I am getting a little lazy these days, I would like to write more articles about software architecture, design patterns or fancy techs like MongoDb and so on…. but I am moving to another country and packing an entire house is taking away all my time and energies.

So this is just a quick post showing a couple of ways to detect the current culture in javascript. Probably just a reminder for my sloppy memory 🙂

Based on the docs on the MDN website, the window.navigator object exposes a language property that represents  the preferred language of the user, usually the language of the browser UI. 

The compatibility is quite good except as usual for IE Mobile, however there are two valid alternatives, userLanguage and browserLanguage.

In case you want the list of all the preferred languages for the user, there’s an experimental property you can exploit, navigator.languages. That’s an “experimental technology”, so the compatibility list is still short (eg. Chrome and Firefox, as usual). It’s a string array containing the list of the user’s preferred languages, with the most preferred language first. 

Based on the docs, navigator.language should be the first element of the returned array but if I check the values in Chrome I get this:

navigator.languages -> [“it-IT”, “it”, “en-US”, “en”]
navigator.language -> “en-GB”

Weird, isn’t it?

My guess is that navigator.languages returns the list of the user system preferred languages, while navigator.language gives instead the current browser’s language. 

Searching on StackOverflow there’s a good answer to the question, I have extracted the code in this gist (link in the code):