Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make javascript variable global

I need to make this data variable global:

$.ajax({
    url: "get_data.php",
    cache: false,
    dataType: 'json',
    data: {},
    success: function(data) {
        for(var i = 0; i < data.results.length; i++) {
            if(my_data.hasOwnProperty(data.results[i].id)) {
                my_data[data.results[i].id].name = data.results[i].name;
            }
        }
    });

I want to have this globally declared. Do I need to declare it as array?

like image 628
user123_456 Avatar asked Jul 01 '12 16:07

user123_456


People also ask

How do you make a global variable in JavaScript?

Global Variables are the variables that can be accessed from anywhere in the program. These are the variables that are declared in the main body of the source code and outside all the functions. These variables are available to every function to access. Var keyword is used to declare variables globally.

Is there a global variable in JavaScript?

Global ScopeGlobal variables can be accessed from anywhere in a JavaScript program. Variables declared with var , let and const are quite similar when declared outside a block.

Can you make a variable global?

Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.


1 Answers

Any variable can be "made global" by attaching it as a property of the window.

window.data = data;

You can now access data as a global variable.

like image 126
Niet the Dark Absol Avatar answered Nov 01 '22 00:11

Niet the Dark Absol