0
 $(document).ready(function() {
   $.wordlist = []; 
   $.get('../wordlist.txt', function(data){
     $.wordlist = data.split('\n');
   });
   console.log($.wordlist);
 });

The console.log($.wordlist) consistently returns an empty array. The same console.log call in the $.get() function successfully returns the complete array.

What am I doing wrong and how do I make this array globally accessible?

Ryan Foley
  • 115
  • 2
  • 5

1 Answers1

1

The $.get method is asynchronous. This means it is still executing when console.log is run. You need to place all code which relies on the data returned by the request within the callback function:

var wordlist = []; 
$.get('../wordlist.txt', function(data){
    wordlist = data.split('\n');
    console.log(wordlist);
});

Also note that it's not a good idea to add your own variables to the jQuery ($) namespace.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339