This page looks best with JavaScript enabled

Object vs. Prototype Properties in Javascript

 ·   ·  ☕ 2 min read

Check if a given object has a specified property. You can either use non-enumerable props or hasOwnProperty.

Consider the below code -

1
2
3
4
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?

1
2
3
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.

1
2
3
4
5
6
7
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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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]);
}
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things