Christian
Christian

Reputation: 7419

Is there a need to use hasOwnProperty with Object.keys?

if I iterate over an object, I need to check whether it is not a prototype object I loop over. (with hasOwnProperty)

If I collect the keys with Object.keys, I always just get the "real keys" back. Is this correct?

Upvotes: 2

Views: 530

Answers (2)

sezanzeb
sezanzeb

Reputation: 1119

No, there is no need:

class A {
    foo = 1
}

A.prototype.bar = 2

a = new A()

for (const key in a) {
    console.log(
        'key in', {
            key,
            hasOwnProperty: a.hasOwnProperty(key),
        }
    )
}

for (const key of Object.keys(a)) {
    console.log(
        'object.keys', {
            key,
            hasOwnProperty: a.hasOwnProperty(key),
        }
    )
}

prints

key in { key: 'foo', hasOwnProperty: true }
key in { key: 'bar', hasOwnProperty: false }
object.keys { key: 'foo', hasOwnProperty: true }

As you can see, key in iterates over both foo and bar, while object.keys only iterates over foo.

Upvotes: 0

alex
alex

Reputation: 490123

Yes, Object.keys() gives you the keys of the properties directly on the object. So you could use that.

Keep in mind that Object.keys() may not be supported in every one of your target browsers if you're doing front-end development.

Upvotes: 0

Related Questions