Skip to content Skip to sidebar Skip to footer

Can't Access Variable (array) From Another Function (defined In Global Scope)

I'd like to use a variable (array) from another function. I already defined it in global scope, but it doesn't work.. Here is my code for better understanding: var globalData = '';

Solution 1:

The problem is that the variable data is being shadowed within the callback function.

function(data) {

    globalData = data;                                  
    data = globalData.name;

    console.log(data); // works just fine  
...

So function(data) established a local variable scoped to the function. Then the bizarre assign and reassign thing happens. You want to believe you are manipulating the global version of data but you are only dealing with the scoped version.

So, the variable data must be passed to the function.

If you prefer to use the global (not recommended), all you have to do is change the function declaration from (data) to some other identifier.


Solution 2:

The problem is that you have two variables with name data one is local to call back and other is global. So when the following line

data = globalData.name;

doesn't change the global variable it just changes the local variable.

One solution is to have different name for global variable.

var globalData = '';
var data2 = '';

$.getJSON('https://...' + data[x].id + '.json', function(data) {

    globalData = data;                                  
    data2 = globalData.name;

    console.log(data2); // works just fine                                   

    if (condition === 1) {
        function2(); // calls this function
    } else {
        function3();
    }
});

function function2() {
    console.log(data2); // just an empty line
}

Solution 3:

You are using the same variable name for two different things. You have a variable named data in your global scope and the getJSON callback function parameter also has a parameter called data which hides the data global variable. Also, inside that callback, you are modifying the data variable. If you intend to modify the data passed as parameter, this is not a good practice.


Post a Comment for "Can't Access Variable (array) From Another Function (defined In Global Scope)"