for
loops are meant to iterate
while incrementing/decrementing.
// note that I'm making this big and ugly to show what's going on
var incrementor = 1, length = 10,
array = [ "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten" ];
for (; incrementor <= length; incrementor = incrementor + 1) {
console.log(incrementor); // 1,2,3,...,10
console.log( array[incrementor - 1] ); // "one", "two", "three", ..., "ten"
}
for ... in ...
loops are meant to enumerate
through object properties.
var object = { "key1" : "one", "key2" : "two", "key3" : "three" },
key = "";
for (key in object) {
console.log(key); // "key1", "key2", "key3"
console.log( object[key] ); // "one", "two", "three"
}
The reason you use for
for arrays is because on bad browsers, for ... in ...
can include not only the number properties (ie: key=0, key=1,...
), but it can also enumerate through things you don't want it to... ...like key=splice, key=length, key=unshift
.
Not really a good thing if you're running this code on a professional site, or for specialized versions of JS being run on specific hardware, or being run as a scripting language in a program like Unity or Unreal Editor's UnrealScript.
The reason you don't use an iterator
on objects is because you don't normally make objects like:
var obj = { "0" : "zero", "1" : "one", "2" : "two" };
And even if you did (jQuery does something like this, for example), there might be word-based properties that you want to enumerate over, but you can't, because you're counting.
Also important to note: enumerating
with for ... in ...
isn't standardized in its functionality.
What this means is that it's not 100% guaranteed to spit the values out in the order you're expecting them in.
If you're relying on your loop going 0,1,2,3,...
then for ... in ...
can't guarantee that 100% of the browsers will do it that way, 100% of the time - even if most browsers get it right most of the time.
Most-frequently, they go by the first-in, first-out rule, now.
If you build your object like { one : 1, two : 2, three : 3 }
, any modern browser will print 1,2,3
. If you build your object like: { two: 2, one: 1, six: 6 }
, you'll get 2,1,6
.
But that's a 95% of the time "should", not a 100% of the time "will".