There's something bugging me with javascript for loop : the extra work to loop though all elements of an array. Suppose I want to alert each element of an array, there are three ways of doing it.

First, you loop with an index and assign the element to a variable.

var items = ["a", "b", "c"];
  for (var i = 0; i < items.length; i++) {
    var item = items[i];
    alert(item);
  }
You always have to have that extra assignment at the beginning of the loop.

Second, you loop with a for each.

var items = ["a", "b", "c"];
  for (var i in items) {
    var item = items[i];
    alert(item)
  }
In javascript, the for each loops though the index of the array instead of looping though the elements, like in most other languages. Thus, you also have to make the extra assignment at the beginning of the loop.

The easiest way of doing it is the third one.

var items = ["a", "b", "c"];
  for (var i = 0, item; item = items[i]; i++) {
    alert(item);
  }

How does it work? First it uses multi-assignment on one line. In javascript, you could write var i = 0, j = 1; and it would create two variables, i and j.

The second part of the for is confusing : it assigns the item but it never check if i it is out of bounds of the array (using i < items.length). It works because when javascript tries to assign an item after the end of the array (in our case items[3]), it returns null which is considered by javascript as false.