public
Created

Why `for (var x in obj) {}` is the devil

  • Download Gist
for-in-fail.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
(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);
});
}());

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!

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.