DEV Community

solring
solring

Posted on

[JS newbie] Array indexes in for...in loops.

TL;DR. The indexes got in this way may not be what you anticipated.

If your are using for(idx in arr) to enumerate through an Array, note that the type of idx is actually string, not number.

> for(i in arr) { console.log(`type of key ${i}: ${typeof(i)}`) }
type of key 0: string
type of key 1: string
type of key 2: string
type of key 3: string
type of key 4: string
Enter fullscreen mode Exit fullscreen mode

That is, if you want to derive some values from the index in your loop like this:

for (i in arr) {
    let val = i + 1 + arr2[i-1];
    // will probably become sth like "0122" rather than a number.
}
Enter fullscreen mode Exit fullscreen mode

Your code will either explode or behave unexpectedly.

This is because the indexes of an Array are actually enumerable properties of an Object and are of type string. The MDN doc has some explanation, and you can also check the indexes of an Array as properties by Object.getOwnPropertyNames.

> Object.getOwnPropertyNames(arr)
[ '0', '1', '2', '3', '4', 'length' ]
Enter fullscreen mode Exit fullscreen mode

Also, it is suggested that you'd better not use this to iterate through an Array if the order of execution is important since it is arbitrary according to MDN doc.

That's today's joke. Sorry if there is any misunderstanding and corrections are appreciated!.

Top comments (0)