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?