

But still we should be aware of the difference. The speedup may only matter in bottlenecks. The for.in loop is optimized for generic objects, not arrays, and thus is 10-100 times slower. So if we need to work with array-like objects, then these “extra” properties can become a problem. That is, they have length and indexes properties, but they may also have other non-numeric properties and methods, which we usually don’t need. There are so-called “array-like” objects in the browser and in other environments, that look like arrays. The loop for.in iterates over all properties, not only the numeric ones. Methods push/pop run fast, while shift/unshift are slow.Īlert( arr ) // Apple, Orange, Pearīut that’s actually a bad idea. And if you need arbitrary keys, chances are high that you actually require a regular object. Arrays are carefully tuned inside JavaScript engines to work with contiguous ordered data, please use them this way. Please think of arrays as special structures to work with the ordered data.

Add a non-numeric property like arr.test = 5.Array-specific optimizations are not suited for such cases and will be turned off, their benefits disappear. We can add any properties to them.īut the engine will see that we’re working with the array as with a regular object. That’s possible, because arrays are objects at their base. Fruits = 5 // assign a property with the index far greater than its lengthįruits.age = 25 // create a property with an arbitrary name
