

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Why is using “for…in” loop in JavaScript array iteration a bad idea?
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.
<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.
<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
- Related Questions & Answers
- Why is using “for…in” with array iteration a bad idea in javascript?
- Why is using the JavaScript eval() function a bad idea?
- Why importing star is a bad idea in python
- Why circular reference is bad in javascript?
- Why eating the raw food is bad for health?
- Reversing a string using for loop in JavaScript
- Iteration of for loop inside object in JavaScript to fetch records with odd CustomerId?
- Why do I sweat too much, Is it bad for me?
- What is for loop statement in JavaScript?
- Why are "continue" statements bad in JavaScript?
- Why “using namespace std” is considered bad practice in C++
- What is for...in loop statement in JavaScript?
- Write a number array and using for loop add only even numbers in javascript?
- How to show for loop using a flowchart in JavaScript?
- Why combination of twitter and facebook is bad