Tag Archives: javascript

foreach in JavaScript

I assume you know about JavaScript’s for (key in object) loop and the function hasOwnProperty.

hasOwnProperty filters inherited properties. You might write your for-in-loop like this:

var my_obj = {
	foo: "bar"
};

function my_map(my_obj) {
	var key;
	for (key in my_obj) {
		if (my_obj.hasOwnProperty(key)) {
			console.log(key, my_obj[key]);
		}
	}
}

But there is a case that will fail. Can you see it? What do you think happens if I give it this object?

var my_obj = {
	hasOwnProperty: function () {
		return false;
	},
	"nothing to see here": "move along"
};

So what’s the solution?

function my_map(my_obj) {
	var key;
	for (key in my_obj) {
		if (Object.prototype.hasOwnProperty.call(my_obj, key)) {
			console.log(key, my_obj[key]);
		}
	}
}

Now isn’t that cool?