Skip to content

Instantly share code, notes, and snippets.

@jpoehls
Created May 5, 2013 14:43
Show Gist options
  • Save jpoehls/5521004 to your computer and use it in GitHub Desktop.
Save jpoehls/5521004 to your computer and use it in GitHub Desktop.
hasOwnProperty() example
function rightWay(obj) {
for (var key in obj) {
// Ignore properties that are inherited.
if (!obj.hasOwnProperty(key)) {
continue;
}
console.log(key);
}
}
function wrongWay(obj) {
for (var key in obj) {
console.log(key);
}
}
// You start out with code like this.
var obj = {};
obj.x = 1;
obj.y = 2;
wrongWay(obj);
// .. which logs `x` and `y`.
// Then one day you use a new library that extends
// a base prototype without making the new property non-enumerable.
Object.prototype.answer = 42;
// Suddenly your code breaks because it is including the new property
// that it didn't expect.
wrongWay(obj);
// .. now logs `x`, `y`, and `answer` (from the prototype).
// You could have protected yourself by using
// `hasOwnProperty()` to ensure you only iterated
// over the properties on the object itself.
rightWay(obj);
// .. logs `x` and `y`, ignoring `answer` because it is on the prototype.
// Also the library author could have made `answer` non-enumerable
// to help avoid this problem but using `hasOwnProperty()`
// is still best-practice unless you /want/ to include
// the prototype's properties, of course.
@lifeinchords
Copy link

thanks for the simple explanation

@tejasmob
Copy link

This is awesome explanation. To the point. Thanks 👍

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