IvanJijon
IvanJijon

Reputation: 447

Difference between Object.keys() and Object.hasOwnProperty()?

When testing if an object has a key we can use Object.keys() or Object.hasOwnProperty().

Consider an object { a: 1 }.

console.log(Object.keys({ a: 1 })); // [ 'a' ]

Now, whe I use Object.hasOwnProperty() I get true:

console.log('a' in { a: 1 }); // true

console.log({ a: 1 }.hasOwnProperty('a')); // true

But if I use Object.keys() I get false :

console.log('a' in Object.keys({ a: 1 })); // false

Why is it false?

Upvotes: 0

Views: 334

Answers (2)

Jackson
Jackson

Reputation: 1223

Lets see some docs first

The Object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would. [1]

The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).[2]

Now consider an object { a: 1 }.

console.log(Object.keys({ a: 1 })); // [ 'a' ]

Available keys in array = 'a'

Using Object.hasOwnProperty()

console.log({ a: 1 }.hasOwnProperty('a')); // true

Is equivalent to

const object1 = new Object();
object1.a = 1;
console.log(object1.hasOwnProperty('a')) // true

Finally, consider this

console.log('a' in Object.keys({ a: 1 })); // false

With reference to the docs for in

The in operator returns true if the specified property is in the specified object or its prototype chain. This is not the same as the prior 2. This is equivalent to

console.log('a' in ['a'])

which is false since there is no property 'a' in ['a']

i.e.

console.log(['a'].hasOwnProperty('a')); // returns false

Upvotes: 1

IvanJijon
IvanJijon

Reputation: 447

Actually Object.keys({ a: 1 }) will return [ 'a' ] which is an Array containing the object's keys. This statement will return false :

console.log('a' in ['a']); // false

So you could use :

console.log(Object.keys({ a: 1 }).includes('a')); // true

But it's more straight forward to simply use :

console.log({ a: 1 }.hasOwnProperty('a')); // true

Upvotes: 3

Related Questions