javascript for loop counter coming out as string [duplicate]

Quoting from MDN Docs of for..in,

for..in should not be used to iterate over an Array where index order is important. Array indexes are just enumerable properties with integer names and are otherwise identical to general Object properties. There is no guarantee that for...in will return the indexes in any particular order and it will return all enumerable properties, including those with non–integer names and those that are inherited.

Because the order of iteration is implementation dependent, iterating over an array may not visit elements in a consistent order. Therefore it is better to use a for loop with a numeric index (or Array.forEach or the non-standard for...of loop) when iterating over arrays where the order of access is important.

You are iterating an array with for..in. That is bad. When you iterate with for..in, what you get is the array indices in string format.

So on every iteration, '0' + 5 == '05', '1' + 5 == '15'... is getting printed

What you should be doing is,

for (var len = grid.length, i = 0; i < len; i += 1) {
    console.log('row:');
    console.log(grid[i] + 5);
}

For more information about why exactly array indices are returned in the iteration and other interesting stuff, please check this answer of mine


You should use a normal for loop rather than a for...in loop for arrays.

for (var row = 0, l = grid.length; row < l; row++) {
  console.log('row:');
  console.log(5 + row);
}

I think this is what your expected output should be.

Fiddle