2

I have read about "hoisting" and "scope" and "callbacks" but I am still unable to solve a simple problem.

First, I define a global array in JavaScript (at the top of the page):

var thefileNames = [];

I use a jQuery function to get the contents of a folder and store them in this array:

jQuery.get(order, function(data) {
  $(data).find("a:contains(.txt)").each(function() {
    thefileNames.push($(this).attr("href"));
    console.log(thefileNames);
  })
});

In the console, I will see an update for each file in the directory, until I end up with something like this at the end (there are 3 files there):

File1.txt
File2.txt
File3.txt

So the information is clearly in "thefileNames". However, if I go anywhere else in my code and use:

console.log(thefileNames);

I will get this result:

[]

I do not understand this given that "thefileNames" is a global variable. Why is the value getting erased once I leave the jQuery function?

31piy
  • 23,323
  • 6
  • 47
  • 67
Kalif Vaughn
  • 353
  • 2
  • 5
  • 10
  • The information in the question is too fragmentary for us to help you. **When** and **where** do you do the `console.log` in relation to the `get`? My guess is that you have [a timing problem](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call), but it's impossible to say without more information. – T.J. Crowder Dec 21 '17 at 07:22
  • 1
    _I go anywhere else in my code_ where is that code? Please update the post with an [MCVE](https://stackoverflow.com/help/mcve). – 31piy Dec 21 '17 at 07:22
  • `However, if I go anywhere else in my code`-> where? on same page ? or on other page? in same page under same ``? – Alive to die - Anant Dec 21 '17 at 07:22
  • (from mobile)..on body load = function a() which has the jQuery get function. If I do console.log anywhere inside function A it's [] unless specifically inside the jQuery bit. – Kalif Vaughn Dec 21 '17 at 07:26

1 Answers1

5

You're retrieving your fileNames by an asynchronous manner so if you put a console.log(thefileNames ) somewhere in your code, at the time the log is executed, your thefileNames array is still empty

Faly
  • 13,291
  • 2
  • 19
  • 37