Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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

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
Something went wrong with that request. Please try again.