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..inwill 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..inisn’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
Here is an example Using normal iteration loops
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
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.