- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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” with array iteration a bad idea in javascript?
Using for..in loops in JavaScript with array iteration is a bad idea because of the following behavior −
Using normal iteration loops −
Example
let arr = [] arr[4] = 5 for (let i = 0; i < arr.length; i ++) { console.log(arr[i]) }
Output
undefined undefined undefined undefined 5
If we had iterated over this array using the for in construct, we'd have gotten −
Example
let arr = [] arr[4] = 5 for (let i in arr) { console.log(arr[i]) }
Output
5
Note that the length of the array is 5, but this still iterates over only one value in the array.
This happens because the purpose of the for-in statement is to enumerate over object properties. This statement will go up in the prototype chain, also enumerating over inherited properties, a thing that sometimes is not desired.
- Related Articles
- Why is using “for…in” loop in JavaScript array iteration a bad idea?
- 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 is using onClick() in HTML a bad practice?
- Why are "continue" statements bad in JavaScript?
- Why “using namespace std” is considered bad practice in C++
- Why eating the raw food is bad for health?
- Iteration of for loop inside object in JavaScript to fetch records with odd CustomerId?
- Convert JavaScript array iteration result into a single line text string
- Why do I sweat too much, Is it bad for me?
- Why is wool called a bad conductor of heat?
- Join every element of an array with a specific character using for loop in JavaScript
- Why python for loops don't default to one iteration for single objects?
- All permutations of a string using iteration?

Advertisements