Why is using “for…in” for array iteration a bad idea in JavaScript?

The purpose of the for-in statement is to enumerate over object properties. This statement will go up in the prototype chain, also enumerating over inherited properties, a thing that sometimes is not desired.

There are three reasons why you shouldn’t use for..in to iterate over array elements:

  • for..in will loop over all own and inherited properties of the array object which aren’t DontEnum; that means if someone adds properties to the specific array object or changed Array.prototype (which is considered bad practice in code which is supposed to work well with other scripts), these properties will be iterated over as well; inherited properties can be excluded by checking hasOwnProperty(), but that won’t help you with properties set in the array object itself
  • for..in isn’t guaranteed to preserve element ordering
  • it’s slow because you have to walk all properties of the array object and its whole prototype chain and will still only get the property’s name, ie to get the value, an additional lookup will be required

Source: https://stackoverflow.com/

Here is example Using normal iteration loops

Output:

using for in for array iteration a bad idea

Do comment if you have any doubts and suggestions on this tutorial.

Note: All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.