I am having trouble understanding how this for-loop terminates in JavaScript:
var files = ["A", "B"];
for (var i = 0, f; f = files[i]; i++) {
console.log(f);
}
When run, it displays A and B on the screen, but why does f=files[2] end the loop? If I run f=files[2]
in my console I get the answer "undefined", so what is the rationale behind the fact that this should end the loop?
Bonus question: Why not write the loop instead as the following?
for (var i=0; i < files.length; i++) {
f = files[i];
console.log(f);
}
This seems clearer and more maintainable to me, so is there some reason that the first piece of code would be used over the second?