0

My javascript function doesn't return anything. I really don't get it. Is it a problem of variable scope?

function getLanguage(){
    navigator.globalization.getLocaleName(
        function(locale){
            var lan = locale.value;
        },
        function(){
            var lan = null;
        }
    );
    return lan;
}

Thank you!

3
  • 3
    Yes, scope is the issue. Define lan before navigator.globalization.getLocaleName Commented Dec 21, 2014 at 20:31
  • It is returning lan; did you check to see what its value is? Commented Dec 21, 2014 at 20:33
  • If you want to avoid callback-soup use Promises: developer.mozilla.org/en/docs/Web/JavaScript/Reference/… Commented Dec 21, 2014 at 20:43

1 Answer 1

4

This is a duplicate of the old asynchronicity problem, but there's a second issue as well -- scope.

First of all, scope. The lan variable is defined inside the internal function, and so cannot be seen from outside.

function getLanguage(){
    var lan;
    navigator.globalization.getLocaleName(
        function(locale){
            lan = locale.value;
        },
        function(){
            lan = null;
        }
    );
    return lan;
}

That was easy. But it still won't work, due to asynchronity. You have to set up your function to use a callback instead:

function getLanguage(callback){
    navigator.globalization.getLocaleName(
        function(locale){
            callback(locale.value);
        },
        function(){
            callback(null);
        }
    );
}

Also, by now, we don't even need the variable, so i got rid of it.

Then, you call it as:

getLanguage(function(lan){
    // something with lan here
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.