Skip to content

Instantly share code, notes, and snippets.

@coolaj86
Created April 25, 2011 22:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coolaj86/941362 to your computer and use it in GitHub Desktop.
Save coolaj86/941362 to your computer and use it in GitHub Desktop.
Why `for (var x in obj) {}` is the devil
(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);
});
}());
@amb26
Copy link

amb26 commented Apr 18, 2012

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment