Created
April 25, 2011 22:09
-
-
Save coolaj86/941362 to your computer and use it in GitHub Desktop.
Why `for (var x in obj) {}` is the devil
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
(function () { | |
"use strict"; | |
var arr = [ | |
'a', | |
'b', | |
'c' | |
] | |
, x; | |
Array.prototype.dummy = function () {}; | |
// first off, never declare `var x` (or `var i`) in a for loop! | |
for (x in arr) { | |
console.log(x); | |
} | |
// 'dummy' will be output... which is WRONG | |
// good | |
for (x in arr) { | |
if (arr.hasOwnProperty(x)) { | |
console.log(x); | |
} | |
} | |
// 'dummy' will not be output | |
// better | |
arr.forEach(function (x) { | |
console.log(x); | |
}); | |
// for objects | |
Object.keys(obj).forEach(function (x) { | |
console.log(x); | |
}); | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Title should be "Why for (var x in arr) {} is the devil". for var in general objects is perfectly reasonable - the error is committed by the person who inserted material into Object.prototype. Noone is realistically going to use the verbose and inefficient construct Object.keys(obj).forEach(function (x) for iteration!