Search code examples
javascripttypeoffor-in-looparray-key

Why does the typeof a numerical array index in a "for..in" loop considered a string?


I noticed that in Javascript a variable used as the index in a for..in loop will be always a string even if I define it the following way:

var s_array = new Array();
s_array[0] = 'foo';
s_array[1] = 'bar';

for(i in s_array){
 alert(typeof(i)); // String
}

Why is it considered a string and not a number?


Solution

  • The for(x in y) syntax is intended to iterate over the properties of an object (not the indexes of an array), and property names are always stored as strings.

    The fact that it also works for arrays is a side effect of array elements being properties on the array object.

    To understand the difference, consider this code:

    var s_array = new Array();
    s_array[0] = 'foo';
    s_array[1] = 'bar';
    s_array['foo'] = 'bar';
    
    console.log("Object:");
    for(i in s_array) {
     console.log(i);   
    }
    console.log("Array:");
    for(var i = 0, l = s_array.length; i < l; i++) {
     console.log(i);   
    }
    

    which provides the following output:

    Object:
    0
    1
    foo
    Array:
    0
    1
    

    There's a foo property on the object, but it's not actually an element inside the array.