About Jamie on Software

Jamie on Software is the online journal of web developer and writer Jamie Rumbelow.

Jamie likes books, guitars, programming, open source and food. He writes about these things too. This is where he puts the things he writes.

Tags
Tweets
Feeds
We Love
Powered by Squarespace
Saturday
Apr092011

JavaScript Iterators

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.

PrintView Printer Friendly Version

EmailEmail Article to Friend

Reader Comments (1)

I hope you don't use append in a loop

March 27, 2012 | Unregistered Commentermcka

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>