Last Updated: February 25, 2016
·
5.747K
· ytilis

For Each Loops Are Broken in IE8 and below

A relatively little known, and even less appreciated, way of doing a for loop in javascript works as follows:

for (key in array) {
    var element = array[key];
    …
}

You might recognize this as essentially the equivalent of the foreach loop in php and other languages. It’s a very useful structure when dealing with associative arrays, or just to save yourself some typing. Unfortunately, there are some quirks with this approach. Notably, as usual, in Internet Explorer.

While at work today I was looping through some form elements, in case the page the script would ran on had multiple forms. Though my test page only had a single form element in it, IE gave me multiple additional elements, such as the letter p, and the number 13…

It did the same for the form.elements array within an inner loop. Seems to be an issue in IE8 and below in the manner in which it handles the for each loop syntax.

As a substitute, I highly recommend instead making use of the jQuery.each function if you're using jQuery (you should be).

Reference can be found here: http://api.jquery.com/jQuery.each/