This page looks best with JavaScript enabled

Non-enumerable Properties in Javascript

 ·   ·  ☕ 2 min read

When you define a prototype for an object you run the risk of counting that as an object property. Use non-enumerable to avoid doing that.

Consider this -

1
2
3
4
5
6
7
8
9
Object.prototype.colors = () => {
  return;
};

let fruits = ["apple", "orange"];
console.log("fruits length: ", fruits.length);

for (fruit in fruits) console.log(fruit);
// 0 1 colors

Even though the array has two elements, it ends up showing the index 0, 1 and ‘colors’ which is the defined prototype.

This can be avoided in two ways -

1
2
3
for (fruit in fruits) {
  if (fruits.hasOwnProperty(fruit)) console.log(fruit); // 0 1
}

Or, simpler still - define prop as non-enumerable in the prototype.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
Object.defineProperty(
  Object.prototype,
  (colors = () => {
    return;
  }),
  { enumerable: false }
);

let fruits = ["apple", "orange"];
console.log("fruits length: ", fruits.length);

for (fruit in fruits) {
  console.log(fruit); // 0 1
}

I end up using this option most of the times since I define prototypes once but use it multiple times and at multiple occasions. It is easy to forget that I defined a custom prop and spend far too much time debugging stupid issues.

Of course, you can do it only if the prop is non-enumerable indeed.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things