Why Using for..in with Array Iteration is 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.

Updated on: 2019-09-19T06:57:52+05:30

126 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements