Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Why `for (var x in obj) {}` is the devil
(function () {
"use strict";
var arr = [
, x;
Array.prototype.dummy = function () {};
// first off, never declare `var x` (or `var i`) in a for loop!
for (x in arr) {
// 'dummy' will be output... which is WRONG
// good
for (x in arr) {
if (arr.hasOwnProperty(x)) {
// 'dummy' will not be output
// better
arr.forEach(function (x) {
// for objects
Object.keys(obj).forEach(function (x) {

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