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 -
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 -
for (fruit in fruits) {
if (fruits.hasOwnProperty(fruit)) console.log(fruit); // 0 1
}
Or, simpler still - define prop as non-enumerable in the prototype.
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.