Skip to content

Instantly share code, notes, and snippets.

@nikahmadz
Created February 11, 2018 09:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nikahmadz/f78e0f56270bf004eeee8909b60c124c to your computer and use it in GitHub Desktop.
Save nikahmadz/f78e0f56270bf004eeee8909b60c124c to your computer and use it in GitHub Desktop.
Never use for..in loop in Javascript
// Somewhere deep in your JavaScript library...
Array.prototype.foo = 1;
// While you have no idea that your code will misbehave.
var a = []; // Create a new empty array.
a[5] = 5; // Perfectly legal JavaScript that resizes the array.
// normal loop saves you
console.log('-- normal for loop --');
for (var i = 0; i < a.length; i++) {
// Iterate over numeric indexes from 0 to 5, as everyone expects.
console.log(a[i]);
}
// but for in loop troubles you
console.log('-- for-in loop --');
for (var x in a){
// Now foo is a part of EVERY array and
// will show up here as a value of 'x'.
console.log(x);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment