Disadvantages of using for..in loop in JavaScript
Last Updated :
23 Feb, 2021
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>
Array.prototype.myCustomProp = "Hello World" ;
let arr = [1, 2, 3, 4, 5];
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>
Array.prototype.myCustomProp = "Hello World" ;
let arr = [1, 2, 3, 4, 5];
for ( var index in arr) {
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++) {
console.log(arr[i]);
}
console.log( "Using for..in loop" );
for ( var index in arr) {
console.log(arr[index]);
}
</script>
|
Output :
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...