user2821275
user2821275

Reputation:

Javascript: For in loops iterating over properties or indices?

Just started learning Javascript. Recently I used a for-in loops to iterate over properties of an object. For example...

var someObject = { a:1, b:2 };

for(var property in someObject){
    console.log(property);
}

This would print...

"a"
"b"

However, when I use it to iterate over an array...

var someArray = ["a","b","c"];

for(var element in someObject){
    console.log(element);
}

The indices, rather than the elements, get printed...

"0"
"1"
"2"

Why is this the case? In general, do JS for-in loops print properties only when iterated over objects and indices for everything else?

If it prints indices with the exception of objects, why would one ever use a classic for loop such as

for(var i=0,i<someNumber,i++)

when one can just use a for in loop? Especially since this seems a lot more concise?

for(var i in something)

Am I even supposed to use for-in loops for anything besides objects?

Thanks!

Upvotes: 1

Views: 259

Answers (1)

thefourtheye
thefourtheye

Reputation: 239653

Quoting from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#Description

for..in should not be used to iterate over an Array where index order is important. Array indexes are just enumerable properties with integer names and are otherwise identical to general Object properties. There is no guarantee that for...in will return the indexes in any particular order and it will return all enumerable properties, including those with non–integer names and those that are inherited.

Because the order of iteration is implementation dependent, iterating over an array may not visit elements in a consistent order. Therefore it is better to use a for loop with a numeric index (or Array.forEach or the non-standard for...of loop) when iterating over arrays where the order of access is important.

So, Don't rely on for..in for iterating over an Array.

And to answer

The indices, rather than the elements, get printed... Why is this the case?

The answer has already been quoted above.

Array indexes are just enumerable properties with integer names and are otherwise identical to general Object properties.

To confirm that fact, try the following sample code

var myArray = ["A", "B", "C"];
for (var i = 0; i < 3; i += 1) {
    console.log(myArray.hasOwnProperty(i));   // will print true
}

That is why for..in works with Arrays as well.

Upvotes: 3

Related Questions