DEV Community

Discussion on: Difference between for...of and for...in loop in JavaScript.

Collapse
 
robinpokorny profile image
Robin Pokorny • Edited

To add one more reason why for..in is bad for arrays is that it skips gaps in sparse arrays:

const arr = ['a']
arr[5] = 'b'

for(const value of arr) {
  console.log(value);
}
// -> a
// -> undefined
// -> undefined
// -> undefined
// -> undefined
// -> b

for(const key in arr) {
  console.log(arr[key]);
}
// -> a
// -> b
Enter fullscreen mode Exit fullscreen mode