For loop ES6 / ES2015

What is diff between below 2s? Why they are not equal?

for (var i = 0 ; i < arr.length ; i++)
for (var i in arr) is for iterating over the properties of an object.

for...of would be more appropriate with an array.

And if all you’re doing is iterating through all of the items in an array, one at a time, starting at 0 - then for...of is fine. The more verbose for loop comes in handy when you have more complex loop conditions.

When using for … in on an array there is no way to know if the items returned are in any particular order. Which is something you often want when using an array.
You should use a regular for loop (the top one) or for … of when order is important.

1 Like

got it… & so… can we say…its in-built bug of javascript?

It is not a bug, there are different tools for different things. for ... in can also be used for objects for example

you mean??..while working with objects… this problem will not occur?..
it will return items in particular order?

Properties on objects are never in a particular order, that’s why it’s not a problem when using it on objects.

1 Like