callum callum - 6 months ago 24
Node.js Question

Is .hasOwnProperty() necessary with for..in in Node.js?

When I do

for..in
, can I dispense with the
if (obj.hasOwnProperty(key)) {...}
check in Node.js if I am careful never to modify
Object.prototype
myself?

Or if I
require()
some third party package that happens to modify
Object.prototype
, does that screw up the
Object.prototype
for my module too?

Answer

Can I dispense with the if (obj.hasOwnProperty(key)) {...} check in Node.js if I am careful never to modify Object.prototype myself?

No, because Object is global. Anyone that messes with it in any module you use (or, any module they use by proxy) and they've broken it for your code regardless of what you do. The property check is damage control. It's a check on the nature of someone mucking with you're implicitly inheriting from.

node_modules/breakit.js

Object.prototype.foobar = () => "borked";
module.exports = true;

run node..

> require('breakit');
true
> let a = {};
> for ( let k in a ) { console.log(k) }
foobar
> a.foobar();
borked

It's important that while the .hasOwnProperty is necessary for the for .. in loop, the loop itself is probably not necessary and better avoided in most cases. The air-bnb eslint style guide for instance bans looping over an object all together.