Archive for category Gotchas

Javascript Gotchas : for vs for…in

Since the day I first acquainted myself with javascript, I thought ‘for’ and ‘’ served pretty much the same purpose. I always considered the latter to be merely of syntactic ease to a developer. Today I found out an important difference between these two constructs.

Suppose we run this code snippet:

var array = [1,2,3,4,5];
array.capacity = 10;

var str = '';
for(var i in array)
  str += array[i];

var str2 = '';
for(i=0; i < array.length; i++)
  str2 += array[i];

So by the end of the code execution, what are the values of str and str2? Before executing this code I always thought both will give the same result but the fact is :
str2 = ‘12345’ while str = ‘1234510’

If the highlighted line(No.2) is removed, both str and str2 give the same value ‘12345’.

If you closely read the description of the for…in consctruct from W3Schools, you’ll find the reason behind this difference in behavior. It says

“The for…in statement loops through the elements of an array or through the properties of an object.”

What entices us to believe that both ‘for’ and ‘’ are alike is the way these have been demonstrated. Almost all the top search result from google, give the code of iterating array elements while explaining the ‘for…in’ construct, so we never use it for accessing properties. Although, we usually do not keep properties in array objects but this behavior results when we get an array object from an external javascript library. Here is the example code for jQuery that reveals this difference:

var a = '[{"a":1},{"a":2},{"a":3}]';
var array = $.parseJSON(a);
for(var i in array)
  //process array[i]

Useful knowledge !

, , ,