Check if a given object has a specified property. You can either use non-enumerable props or hasOwnProperty.
Consider the below code -
Object.prototype.awesomeness = 42;
const earth = {};
console.log(earth["awesomeness"]); // 42
We have defined a prototype that gets attached to any object. Therefore the prop defined by prototype is attached to the object as well.
What if you want to check all props in earth?
for (prop in earth) {
console.log(prop, ":", earth[prop]); // 42
}
Even when the object is empty, the awesomeness prop rears it beautiful head.
We can avoid this incorrect reporting of prop against an object in two ways.
Use hasOwnProperty when checking for props in an object
Check for hasOwnProperty before printing out the prop. Since awesomeness does not satisfy the criteria it does not make the cut.
Object.prototype.awesomeness = 42;
const earth = {};
for (prop in earth) {
if (earth.hasOwnProperty(prop)) console.log(prop, ":", earth[prop]);
else console.log("fake prop");
// fake prop
}
Use defineProperty to set prop
Define prop against prototype using defineProperty and set enumerable to false. This will suppress any unwanted behaviour.
Object.defineProperty(Object.prototype, "awesomeness", {
value: 42,
enumerable: false
});
const earth = {};
for (prop in earth) {
// does not enter loop since there is no prop
console.log(prop, ":", earth[prop]);
}