133

Consider:

if (someVar.hasOwnProperty('someProperty') ) {
 // Do something();
} else {
 // Do somethingElse();
}

What is the right use/explanation of hasOwnProperty('someProperty')?

Why can't we simply use someVar.someProperty to check if an object someVar contains property with name someProperty?

What is a property in this case?

What property does this JavaScript check?

3

13 Answers 13

208

hasOwnProperty returns a boolean value indicating whether the object on which you are calling it has a property with the name of the argument. For example:

var x = {
    y: 10
};
console.log(x.hasOwnProperty("y")); //true
console.log(x.hasOwnProperty("z")); //false

However, it does not look at the prototype chain of the object.

It's useful to use it when you enumerate the properties of an object with the for...in construct.

If you want to see the full details, the ES5 specification is, as always, a good place to look.

Sign up to request clarification or add additional context in comments.

Image
Bonus points for prototype chain. Still trying to figure out what its calling on when its not called on an object... its not window
@KristofferSHansen - I was wondering that too, but the question has been edited so it's now being called on an object. When it's not, an error is thrown.
Image
I suppose that changes things. No error when run from console in Chrome though.
@KristofferSHansen - I think that's because of how the console runs code (it's run as eval code rather than global or function code). I tried it in a blank HTML page and get a "cannot convert null to object" error.
@KristofferSHansen see Kunal Vashist answer when it is called on a class method
46

Here is a short and precise answer:

In JavaScript, every object has a bunch of built-in key-value pairs that have meta information about the object. When you loop through all the key-value pairs using for...in construct/loop for an object you're looping through this meta-information key-value pairs too (which you definitely don't want).

Enter image description here

Using hasOwnPropery(property) filters-out these unnecessary looping through meta information and directly checks that is the parameter property is a user-given property in the object or not. By filters-out, I mean, that hasOwnProperty(property) does not look if, property exists in Object's prototype chain aka meta information.

It returns boolean true/false based on that.

Here is an example:

var fruitObject = {"name": "Apple", "shape": "round", "taste": "sweet"};
console.log(fruitObject.hasOwnProperty("name"));  //true
console.log(Object.prototype.hasOwnProperty("toString")) // true because in above snapshot you can see, that there is a function toString in meta-information

I hope it's clear!

at last line of your example you write console.log(Object.prototype....; did you mean console.log(fruitObject.? fruitObject or Object ?
>"you're looping through this meta-information key-value pairs too" But when I run for (var key in fruitObject) { ... } js only cycle's through non-prototype keys anyway, am I missing something or did JS runtime change the way they handle for key-in-object loops?
Just gave var obj = { "fruit": "apple" }; for (var key in obj) { console.log(key) } a try in both firefox and node, and contrary to this answer it does NOT print __proto__and such.
16

Summary:

hasOwnProperty() is a function which can be called on any object and takes a string as an input. It returns a boolean which is true if the property is located on the object, otherwise it returns false. hasOwnProperty() is located on Object.prototype and thus available for any object.

Example:

function Person(name) {
  this.name = name;
}

Person.prototype.age = 25;

const willem = new Person('willem');

console.log(willem.name); // Property found on object
console.log(willem.age); // Property found on prototype

console.log(willem.hasOwnProperty('name')); // 'name' is on the object itself
console.log(willem.hasOwnProperty('age')); // 'age' is not on the object itself

In this example a new Person object is created. Each Person has its own name which gets initialized in the constructor. However, the age is not located on the object but on the prototype of the object. Therefore hasOwnProperty() does return true for name and false for age.

Practical applications:

hasOwnProperty() can be very useful when looping over an object using a for in loop. You can check with it if the properties are from the object itself and not the prototype. For example:

function Person(name, city) {
  this.name = name;
  this.city = city;
}

Person.prototype.age = 25;

const willem = new Person('Willem', 'Groningen');

for (let trait in willem) {
  console.log(trait, willem[trait]); // This loops through all properties, including the prototype
}

console.log('\n');

for (let trait in willem) {
  if (willem.hasOwnProperty(trait)) { // This loops only through 'own' properties of the object
    console.log(trait, willem[trait]);
  }
}

This is the only complete and correct answer here.
15

It checks:

Returns a Boolean value indicating whether an object has a property with the specified name

The hasOwnProperty method returns true if the object has a property of the specified name, false if it does not. This method does not check if the property exists in the object's prototype chain; the property must be a member of the object itself.

Example:

var s = new String("Sample");
document.write(s.hasOwnProperty("split"));                        //false
document.write(String.prototype.hasOwnProperty("split"));         //true

I gave a -1 because your initial answer was a short and utterly incoherent sentence, which was then updated to a slightly longer, slightly more coherent, but entirely inaccurate sentence.
@amnotiam- but i think its much clear now...its because my internet issue i cannot able to post more..........
3

You use object.hasOwnProperty(p) to determine if an object has an enumerable property p-

An object can have its own prototype, where 'default' methods and attributes are assigned to every instance of the object. hasOwnProperty returns true only for the properties that were specifically set in the constructor, or added to the instance later.

To determine if p is defined at all, anywhere, for the object, use if(p instanceof object), where p evaluates to a property-name string.

For example, by default all objects have a 'toString' method, but it will not show up in hasOwnProperty.

Comments

3

hasOwnProperty is a proper way of checking an object has a property or not. someVar.someProperty cannot be used as an alternative to this situation. The following condition will show a good difference:

const someVar = { isFirst: false };


// The condition is true, because 'someVar' has property 'isFirst'
if (someVar.hasOwnProperty('isFirst')) {
  // Code runs
}


// The condition is false, because 'isFirst' is false.
if (someVar.isFirst) {
  // Code does not runs here
}

Hence someVar.isFirst cannot be used alternative to someVar.hasOwnProperty('isFirst').

Comments

3

2021 - Object.hasOwn as a replacement for Object.hasOwnProperty()

As other answers indicated, hasOwnProperty will check for an object own properties in contrast to in which will also check for inherited properties.

There is a new alternative method called Object.hasOwn() and is intended to be a replacement for Object.hasOwnProperty()

Object.hasOwn() is a static method which returns true if the specified object has the specified property as its own property. If the property is inherited, or does not exist, the method returns false.

const person = { name: 'dan' };

console.log(Object.hasOwn(person, 'name'));// true
console.log(Object.hasOwn(person, 'age'));// false

const person2 = Object.create({gender: 'male'});

console.log(Object.hasOwn(person2, 'gender'));// false

It is recommended to this method use over the Object.hasOwnProperty() because it also works for objects created by using Object.create(null) and for objects that have overridden the inherited hasOwnProperty() method. Although it's possible to solve these kind of problems by calling Object.prototype.hasOwnProperty() on an external object, Object.hasOwn() overcome these problems, hence is preferred (see examples below)

let person = {
  hasOwnProperty: function() {
    return false;
  },
  age: 35
};

if (Object.hasOwn(person, 'age')) {
  console.log(person.age); // true - the remplementation of hasOwnProperty() did not affect the Object
}

let person = Object.create(null);
person.age = 35;
if (Object.hasOwn(person, 'age')) {
  console.log(person.age); // true - works regardless of how the object was created
}

More about Object.hasOwn can be found here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn

Browser compatibility - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn#browser_compatibility

Comments

2

hasOwnProperty is a normal JavaScript function that takes a string argument.

In your case, somevar.hasOwnProperty('someProperty'), it checks the somevar function has somepropery or not - it returns true and false.

Say

function somevar() {
    this.someProperty = "Generic";
}

function welcomeMessage()
{
    var somevar1 = new somevar();
    if(somevar1.hasOwnProperty("name"))
    {
        alert(somevar1.hasOwnProperty("name")); // It will return true
    }
}

Comments

1

What is the right use/explanation of hasOwnProperty('someProperty') ?

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

const someVar = {};
someVar.someProperty = 'Foo';

console.log(someVar.hasOwnProperty('someProperty'));
// expected output: true

console.log(someVar.hasOwnProperty('someProperty1'));
// expected output: false

Why can't we simply use someVar.someProperty to check if an object someVar contains property with name someProperty ?

someVar.someProperty will return the property value, You can not check that this property is available in the object or not via someVar.someProperty.

Now in ES2022, A new method has been introduced which is Object.hasOwn(<object reference>, <property name>) this method is intended as a replacement for Object.hasOwnProperty() which overcome some limitations of .hasOwnProperty().

Comments

0

For this case someVar is Object. Object has a prototype calls 'hasOwnProperty'. Property means a value for key in Object.

For example:

const objectTest = {key1: property1, key2: property2}
If (objectTest.hasOwnProperty('key1')) {
return true
}
else { return false }

In this case we got true, because key1 has property1.

If you want to check more information for this prototype, you can read there

Comments

0

I'd just like to add that in the case of Object.keys, you don't need hasOwnProperty. Only for for (const key in object) loops.

class Person { name = "foo" }
Person.prototype.age = 25
a = new Person()
console.log(Object.keys(a))

Only prints [ 'name' ]

Comments

-1

Scene A:

const objA = { a: 1, b: 2 }
for (const key in objA) {
  if (objA.hasOwnProperty(key)) {
    console.log(objA[key])
  }
}

    Output

    1
    2

Scene B:

const objB = {
  a: 1,
  b: 2,
  hasOwnProperty() {
    return false
  }
}

for (const key in objB) {
  if (objB.hasOwnProperty(key)) {
    console.log(objB[key])
  }
}

    Outputs nothing

Because JavaScript doesn't protect the property of hasOwnProperty. So you can use it like this:

for (const key in objB) {
  if (Object.prototype.hasOwnProperty.call(obj, key)) {
    console.log(objB[key])
  }
}

Comments

-3

It checks if an object has a property. It works the same as if(obj.prop), as far as I know.

Image
obj.prop follows the prototype chain, hasOwnProperty does not
The problem is when prop has false value. if(obj.hasOwnProperty('prop')) will be true while if(obj.prop) will be false.

Your Answer

Draft saved
Draft discarded

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.