nmyster
nmyster

Reputation: 452

Change a global variable in a function

I can not figure this out...

I want to:

declare a variable, run a function that changes the value of that variable and then then alert the value of the new value.

Like so:

function loadApp(){
    FB.api('/me', function(response) {
            var posLat;
            getLocation();
        console.log(posLat);
    });
}


    function getLocation(){

        posLat = "hey";

}

The alert should display 4 but just alerts undefined. Am i bein stupid?

Upvotes: 0

Views: 97

Answers (1)

David G
David G

Reputation: 96800

posLat is defined inside a function, therefore making it a local function that cannot be used outside of its surround scope. That's why getLocation can't modify it. In fact, it's creating a global variable called posLat on the window object. As the comments on my post suggest, set posLat to the return value of getLocation:

var posLat = getLocation();

...

function getLocation() {
    return "hey";
}

Upvotes: 4

Related Questions