The problem with using 'local' variables in javascript is that your variables actually have function scope, rather than block scope - like Java and C# etc has.
One way to get around this is using let which has block scope, but only firefox supports this currently.
So this code would work in firefox only:
for (var x in files) {
// This variable has BLOCK scope
let file = files[x];
asynchronousFunction(var1, var2, function(){
console.log(file.someVariable);
});
}
For other browsers, the alternative is to use closures
for (var x in files) {
var file = files[x];
asynchronousFunction(var1, var2, (function(file){
return function() {
console.log(file.someVariable);
};
})(file);
}
Another way you could do this is using map/forEach, assuming that the datatype of files is an array.
files.forEach(function(file) {
asynchronousFunction(var1, var2, function(){
console.log(file.someVariable);
});
});
If it's not an array, then you can always use this technique
[].forEach.call(files, function(file) {
asynchronousFunction(var1, var2, function(){
console.log(file.someVariable);
});
});
The fuller way of writing this is of course
Array.prototype.forEach.call(files, function(file) {
// As before
But I feel [].forEach is nicer on the eyes.
x.someVaraiblealways printing the last value?xwill always be a string, not an array element (which appears to be what you're going for).xwill always be a string, and almost certainly not the one you were expecting, becausefor...inloops over property names, not values. (Side note: people shouldn't be usingfor...inin most of the cases where they do. This being a prime example.)