The Evil “for”
As I was working on some JavaScript code this week, I stopped and thought awhile about how I could get around putting a C-style ;for statement. You know what I mean — I was trying to get away from this:
for (i=0; i item = list[i]; // do stuff }
And then I realized something that has always been subtle yet very true to me — I hate the C-style for statement and I avoid it whenever and wherever possible. I think this came about when I started in Python — it’s for statement is very different than the one above. The analogous in Python would be:
for (thing in list): # do stuff
It’s more like an iterator than a traditional for-statement, because you can only have a for statement on a sequence. What to just have the number 1 through 10? Then put them in a sequence with the range function:
for (num in range(1,10)): // do stuff
In Java you can do the C-style if you want to, but I tend to avoid them altogether and use iterators pretty much exclusively:
Iterator it = list.iterator();
while(it.hasNext()) {
Object obj = it.next();
//do stuff
}
JavaScript 1.6 has a forEach closure in it’s Array object, but IE only supports JavaScript 1.5. So I usually do the following:
for (var idx in list) {
var obj=list[idx];
// do stuff
}
Similar to the Python version, but you get the index the Array, not the value. An interesting quirk by a nice one if you have an associative array.
So why don’t I like the traditional, tried-and-true for style? Because I think it’s prone to breakage and delicate. It’s also really a three-statement command: set the value, tell the test command, and increment, in once step. and I tend to typo something in there like:
- Misplace a semicolon
- Use <= instead of just <
- Forget a + at the end of the increment
- Forget a bracket at the end
The less complicate the code, the better off we all our.
May 3rd, 2007 at 1:35 pm
Not to be a smarty pants - but this should be posted in the “Need a Life” category rather than “Life.”