5

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?

Boaz
  • 19,892
  • 8
  • 62
  • 70
talsibony
  • 8,448
  • 6
  • 47
  • 46

3 Answers3

10

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.

Anthony Grist
  • 38,173
  • 8
  • 62
  • 76
  • I find your wording slightly confusing: array indexes are not "mapped" to properties, array elements _are_ properties. Arrays are just like other objects, there's nothing special about them. – georg Oct 03 '13 at 09:48
  • @thg435 Good point, edited. I was trying to indicate that there's a slight difference between array elements as properties and other properties set on the object, but definitely could have worded it better. – Anthony Grist Oct 03 '13 at 09:55
  • first thank you all for the answers, so when I am asking for s_array[1] behind the scene.. there is some conversion of the number 1 to string? – talsibony Oct 03 '13 at 13:58
2

Arrays are essentially objects with managed set of indexed keys.

Since every key in an object is of type string hence it is a string as well.

Consider your array as :

{"0" : "foo" , "1" : "bar"}

So your

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

can be read as

for each key in the s_array

loxxy
  • 12,990
  • 2
  • 25
  • 56
2

In js arrays are high-level, list-like objects (associative arrays).

indexes eventually gets coerced into a string by the JavaScript engine, anyway, through an implicit toString conversion.

source: MDN

shem86
  • 478
  • 4
  • 16