Created
February 11, 2018 09:43
-
-
Save nikahmadz/f78e0f56270bf004eeee8909b60c124c to your computer and use it in GitHub Desktop.
Never use for..in loop in Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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