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.
+ operator can lead to problems.
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 (to get 2), you actually end up concatonating
"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.