Why does the typeof a numerical array index in a "for..in" loop considered a string? [duplicate]
Asked Answered
Q

3

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?

Quintin answered 3/10, 2013 at 9:3 Comment(0)
C
9

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.

Contrastive answered 3/10, 2013 at 9:7 Comment(3)
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.Stoffel
@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.Contrastive
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?Quintin
R
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

Redbug answered 3/10, 2013 at 9:7 Comment(0)
D
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

Dentist answered 3/10, 2013 at 9:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.