title: Storing javascript data in global array not working as expected
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/13487437/change-global-variable-inside-javascript-closure">change global variable inside javascript closure</a>  </p>
  </blockquote>
  
  
  
  <p>I am having a problem storing data in a javascript global array . I can't figure out why the array is empty even though I have assigned it some elements. </p>
  
  <p>Basically I have two functions: <code>loadMarkers</code> is called whenever a user clicks a button and gets some information from a url in JSON, parses that data and stores it in the global array. The other function is <code>showMarkers</code> that just iterates over the array and show all the markers, but that array is empty!</p>
  
  <p>Thansks in advance.</p>
  
  <pre><code>var markers = [];
  
  
  function loadMarkers(url) {
  
      markers = [];
      $.get(url, function(data) {
  
          var json = jQuery.parseJSON(data);
  
          for (var i = 0; i &lt; json.length; i++) {
  
              // parsing json
              var lat = json[i].Latitude;
              var lng = json[i].Longitude;
              var id = json[i].ID;
  
              console.log(id); // this prints with no problems!
  
              // create new marker
              var marker = new google.maps.Marker({
                  position: new google.maps.LatLng(lat, lng),
                  title: id,
                  html: "&lt;p&gt;" + "Info for container " + id + "&lt;/p&gt;"
              });
  
              // add marker to markers array        
              markers.push(markers[i]);
  
              // add info window to marker
              google.maps.event.addListener(marker, "click", function() {
                  infoWindow.setContent(this.html);
                  infoWindow.open(map, this);
              });
          }
      });
  }
  
  function showMarkers() {
      for (i = 0; i &lt; markers.length; i++)
          console.log(markers); // here I get an empty array!
          markers[i].setMap(map);
  }
  </code></pre>