So I’ve got this piece of code below:
var divs = ["A", "B", "C"];
for (var i = 0, div; div = divs[i]; i++) {
print(div);
}
As I understand it, the for loop iterates through every element of the divs array and prints them. I however fail to understand how the loop terminates. Could somebody explain that to me?
The loop terminates because
div = divs[i]will beundefinedwheniis out of bounds.Since
undefinedis a falsey value, the condition is considered to have not been met, and the loop stops.Note that you’re doing an assignment, and not a comparison. The assignment expression returns the value that was assigned, and that value is used for the condition.
You should also note that this technique is reliable only if none of the members of the Array are falsey. If there was a
0in the Array for example, it would terminate early.