Skip to content

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

  • by

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 an example Using normal iteration loops

<!DOCTYPE html>
<html>

<body>
    <script type="text/javascript">
        let arr = []
        arr[4] = 5
        for (let i = 0; i < arr.length; i ++) {
         console.log(arr[i])
     }
 </script>

</body>
</html>

Output:

using for in for array iteration a bad idea

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

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading