JavaScript Iterators
Saturday, April 9, 2011 at 10:00AM Whenever I’m using any other programming language I really miss PHP’s foreach loop. It seems like a brilliantly elegant solution to the problem of looping through an array of elements and pulling out the key and value.
One of the things I’ve always hated in JavaScript is exactly that; looping through an array of elements and doing something.
Let’s say we have this array of data:
var codeigniters = [
'Jamie Rumbelow', 'Jeremy Gimbel', 'Phil Sturgeon', 'Elliot Haughin'
];
I used to use the native JavaScript for in loop, which looks like this:
for (var index in codeigniters) {
$("#codeigniter_masters").append(
"<li>" + codeigniters[index] + "</li>"
);
}
This works fine, but it’s horribly verbose. I also despise the fact that it assigns the iterating variable to the index of the current array element. It’s stupid. I will generally never want just the index. Give me the element itself, for goodness sake.
I’m embarrassed, but I’ve only just discovered there’s a much better way of doing this. Arguably, JavaScript’s most powerful feature is the anonymous function, and it comes to our rescue here in the form of jQuery.each();
$.each(codeigniters, function(index, codeigniter){
$("#codeigniter_masters").append("<li>" + codeigniter + "</li>");
});
That is much, much nicer. It is cleaner, easier to read and makes more sense. And after all, the first of Rumbelow’s rules of good code is every line should make sense.
javascript,
syntax sugar 
Reader Comments (1)
I hope you don't use append in a loop