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.
Syntax:
Array.prototype.myCustomProp = "Hello World";
Now create an array x and assign some value to it and iterate through the for..in the loop.
Javascript
<script> // Adding property using myCustomProp Array.prototype.myCustomProp = "Hello World" ; let arr = [1, 2, 3, 4, 5]; // Iterating using for..in loop for ( var index in arr) { console.log(arr[index]); } </script> |
Output :
1 2 3 4 5 "Hello World"
Solution: You can solve this problem using the hasOwnProperty() method.
Javascript
<script> // Adding property using myCustomProp Array.prototype.myCustomProp = "Hello World" ; let arr = [1, 2, 3, 4, 5]; // Iterating using for..in loop for ( var index in arr) { // Checking if the item is present in arr or not if (arr.hasOwnProperty(index)) { console.log(arr[index]); } } </script> |
Output :
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[0], arr[3], arr[5], it means the arr[1], arr[2], arr[4] are undefined, but the for..in loop ignores them.
Example:
Javascript
<script> let arr = []; arr[0] = "A" ; arr[3] = "D" ; arr[5] = "F" ; console.log( "Using for loop" ); for ( var i = 0; i < arr.length; i++) { // "A", undefined, undefined, "D", undefined, "F" console.log(arr[i]); } console.log( "Using for..in loop" ); for ( var index in arr) { // "A", "D", "F" console.log(arr[index]); } </script> |
Output :
- 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.
Javascript
<script> let arr = [undefined, undefined, undefined, "Hello world" ]; for ( var index in arr) { console.log(arr[index]); } </script> |
Output :
undefined undefined undefined Hello World