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

Front End TechnologyJavascriptObject Oriented Programming

In most of the cases, it is better to use normally a 'for' loop rather than "for...in" loop because the "for...in" loop results in the indexes and won't bother about the leftover indexes whereas the normal "for" loop displays the values and in the leftover indexes a value called  'undefined' will be executed so that a developer will not confuse while writing the code.

syntax-1

for (var x in array) {
// code
};

The above code is the syntax for "for...in" loop.

syntax-2

for () {
// code
};

The above is the syntax for the normal "for" loop.

Example-1

In the following example, initially, the array "num" has only 5 digits(indexes from 0-4). When the other index 7 which is far from index 'four' is added to the array, continuously the indexes have been executed without notifying anything about leftover indexes(5 and 6).  Which is not the case with normal "for" loop. This might perplex the developer. 

 Live Demo

<html>
<body>
<script>
   var num = [1,2,3,4,5];
   num[7] = 7;
   for (var x in num) {
      document.write(x);
      document.write("</br>");
   }
</script>
</body>
</html>

Output

0
1
2
3
4
7


Example-2

In the following example, unlike the "for...in" loop, in normal "for" loop the values are displayed instead of indexes and also in the leftover indexes the value undefined is executed to not to perplex the developer.

 Live Demo

<html>
<body>
<script>
   var num = [1,2,3,4,5];
   num[7] = 7;
   for (var i = 0; i < num.length; i++) {
      document.write(num[i]);
      document.write("</br>");
   }
</script>
</body>
</html>

Output

1
2
3
4
5
undefined
undefined
7
raja
Published on 26-Aug-2019 12:05:31
Advertisements