How to define Global Arrays?

javascript, jquery

Solution

`New` is not a keyword.

Use:

var data = new Array();

Or, more succinctly:

var data = [];

After your edit you mention that the first script block is loaded asynchronously. Your code will not work as written. `data` is a global variable, once it is loaded onto the page. You need to use a callback pattern to properly execute the code.

Since you haven't posted the asynchronous code I am not going to provide a `callback` sample. Though, a quick solution follows:

var interval = setInterval(function(){
    if(data) {
        /* ... use data ... */
        clearInterval(interval);
    }
}, 500);

Problem

Code example: ``` <script> var data = new Array(); data[0] = 'hi'; data[1] = 'bye'; </script> <script> alert(data[0]); </script> ``` This gives the following error: `data is not defined` How do you make something like this work? Especially if the first `<script>` block is being loaded on the page by ajax, and the second block is working from it. jQuery solution is acceptable.

Original source