JavaScript Annoyances: for (i in array)

I got bitten by a JavaScript annoyance today that I figured I’d describe here in case other people have the same problem. I’m not going to call it a bug, because technically it isn’t.

I was looping through an array, using the syntax for (i in a) where i is the array index and a is the array. Inside this loop I needed to do some simple arithmetic, just a basic i + 1. What can go wrong? As it turns out, everything.

Since JavaScript is loosely-typed it just happily converts your variables from one datatype to another whenever it needs to. This is handy when you want to concatonate an integer on the end of a string, or do arithmetic on a number stored as a string. Unfortunately the combination of this loose typing and the overloading of the + operator can lead to problems.

The for (x in y) construct is used to iterate over all of the keys in an object, but the keys it returns are all converted to strings. When you try to add 1 and 1 (to get 2), you actually end up concatonating "1" and "1" (getting "11").

The solution is to use the slightly more verbose for (var i = 0; i < a.length; i++) construct, which leaves i an integer throughout. Alternatively you can use the parseInt() function to turn a string into an integer, or do one of the ugly tricks like subtracting zero or multiplying or dividing by one (we’ve seen that adding zero won’t work because of the overloaded +).

Hopefully in taking the time to write this up I won’t fall for this again.