What is property in hasOwnProperty in JavaScript?

JavascriptObjectHasownproperty

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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!

Solution 3 - Javascript

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

Solution 4 - Javascript

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]);
  }
}

Solution 5 - Javascript

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.

Solution 6 - Javascript

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').

Solution 7 - Javascript

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
    }
}

Solution 8 - Javascript

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

Solution 9 - Javascript

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])
  }
}

Solution 10 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFLYView Question on Stackoverflow
Solution 1 - JavascriptJames AllardiceView Answer on Stackoverflow
Solution 2 - JavascriptOm SaoView Answer on Stackoverflow
Solution 3 - JavascriptPranay RanaView Answer on Stackoverflow
Solution 4 - JavascriptWillem van der VeenView Answer on Stackoverflow
Solution 5 - JavascriptkennebecView Answer on Stackoverflow
Solution 6 - JavascriptRahmat AliView Answer on Stackoverflow
Solution 7 - JavascriptKunal VashistView Answer on Stackoverflow
Solution 8 - JavascriptRan TurnerView Answer on Stackoverflow
Solution 9 - JavascriptLeeKlausView Answer on Stackoverflow
Solution 10 - JavascriptvisualidiotView Answer on Stackoverflow