In this article, we will see what are the disadvantages of using for..in loop and how to solve those issues.
Disadvantages of using for..in loop:
Reason 1: When you add a property in an array or object using the prototype and any other array arr that has no relation with that property when you iterate array x then you get that property.
Example: You added a property myCustomProp to Array.prototype.
Array.prototype.myCustomProp = "Hello World";
Now create an array x and assign some value to it and iterate through the for..in the loop.
1 2 3 4 5 "Hello World"
Solution: You can solve this problem using the hasOwnProperty() method.
1 2 3 4 5
Reason 2 : The for..in loop ignores the undefined values of the array. Suppose you created an empty array arr and assigned some items to arr, arr, arr, it means the arr, arr, arr are undefined, but the for..in loop ignores them.
- Using for loop:
"A" undefined undefined "D" undefined "F"
- Using for..in loop :
"A" "D" "F"
A simple for loop prints all the elements of the array including undefined but for..in loop ignores all the undefined values. But this is true only for the array whose values are not defined but when the undefined is explicitly present in the array then for..in loop does not ignore them.
undefined undefined undefined Hello World