0

I have this code but I am unable to understand why when I print 'globalData' first it prints all values fine but later when I print it again it print just an empty array? I'm new to JavaScript and jQuery.

<script>
  var globalData = [];

  $( document ).ready(function() {

    $.get( "http://....", function( data ) {

      globalData.push(data[i]);
      .
      .
      .

    });
  console.log(globalData);  //["fg", "wedsd", "hjkyu"]
  });

console.log(globalData);    //[]

</script>
11mb
  • 1,339
  • 2
  • 16
  • 33
Mohd Ali
  • 311
  • 2
  • 13
  • This is no duplicate. The problem arises because of other reasons. The OP doesn't try to get a return value from the asynchronous function. – user0815 Mar 16 '15 at 07:50

1 Answers1

1

With $( document ).ready() you only define an anonymous function that is called as soon as the document structure is build successfully. Then you print globalData which is empty at this point. If your defined function gets called, it initializes the globalData and you see the values.

All in all, because the callback function you define gets called asynchronously and the definition itself doesn't block and returns immediately (even if the DOM is not loaded already), you print globalData before it gets filled with values in the callback.

The problem is even unrelated to the Ajax request invoked with $.get even so you run into a similar situation there. But you would get the same problem if you simply fill the array inside the ready callback.

user0815
  • 1,376
  • 7
  • 8