What's the best way to loop through a set of elements in JavaScript? What's the best way to loop through a set of elements in JavaScript? arrays arrays

What's the best way to loop through a set of elements in JavaScript?


Here's a nice form of a loop I often use. You create the iterated variable from the for statement and you don't need to check the length property, which can be expensive specially when iterating through a NodeList. However, you must be careful, you can't use it if any of the values in array could be "falsy". In practice, I only use it when iterating over an array of objects that does not contain nulls (like a NodeList). But I love its syntactic sugar.

var list = [{a:1,b:2}, {a:3,b:5}, {a:8,b:2}, {a:4,b:1}, {a:0,b:8}];for (var i=0, item; item = list[i]; i++) {  // Look no need to do list[i] in the body of the loop  console.log("Looping: index ", i, "item" + item);}

Note that this can also be used to loop backwards (as long as your list doesn't have a ['-1'] property)

var list = [{a:1,b:2}, {a:3,b:5}, {a:8,b:2}, {a:4,b:1}, {a:0,b:8}];    for (var i = list.length - 1, item; item = list[i]; i--) {  console.log("Looping: index ", i, "item", item);}

ES6 Update

for...of gives you the name but not the index, available since ES6

for (const item of list) {    console.log("Looping: index ", "Sorry!!!", "item" + item);}


Note that in some cases, you need to loop in reverse order (but then you can use i-- too).

For example somebody wanted to use the new getElementsByClassName function to loop on elements of a given class and change this class. He found that only one out of two elements was changed (in FF3).
That's because the function returns a live NodeList, which thus reflects the changes in the Dom tree. Walking the list in reverse order avoided this issue.

var menus = document.getElementsByClassName("style2");for (var i = menus.length - 1; i >= 0; i--){  menus[i].className = "style1";}

In increasing index progression, when we ask the index 1, FF inspects the Dom and skips the first item with style2, which is the 2nd of the original Dom, thus it returns the 3rd initial item!


I like doing:

 var menu = document.getElementsByTagName('div');for (var i = 0; menu[i]; i++) {     ...}

There is no call to the length of the array on every iteration.