Javascript “for (x in y)” is stupid

That’s right, the “for (x in y)” used by JavaScript is dumb. And what is more, they can’t change it without royally screwing up people who have worked around it.

When used with arrays, the “x” will represent the index of the array, not the value (as is common in most languages).

Sure, I agree that this is a useful feature to have, but why must it do it by default.

So to recap: To iterate through an array in Javascript using this control structure you must do it as shown below:
[js]
for (key in SomeArray) {
theValue = SomeArray[key];
}
[/js]

Stupid.

3 Responses to “Javascript “for (x in y)” is stupid”

  1. Will says:

    Just be thankful you are using Javascript and not Lua (script). Lua is designed as scripting language easily usable with C but breaks just about every C convention there is (just for the sake of it??). But more on that later.
     
    You could also be forced to use VBScript (as I was recently in my testing subject) – *shudders*
     
    Will.

  2. Rhys says:

    Been there. Done That. (Vb Script in my Masters degree last year). Of course I was cranky it wouldn’t work in anything but Internet Explorer, so I did a JavaScript version for other browsers and used browser sniffing to work out whether it was IE (and hence should disable the JavaScript). I wouldn’t normally use browser sniffing, but seeing as the VB code had to be running when they tested it it seemed like a good idea.

  3. Dave says:

    They could always introduce a foreach statement to use the value instead of the index

Leave a Reply