What is property in hasOwnProperty in JavaScript?
Asked Answered
G

12

132

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?

Genip answered 22/2, 2012 at 14:19 Comment(3)
#2600585Plectognath
When I asked this question I thought it was a function that checked some html. Now I see it checking a javascript object or method for a 'variable' within that object or method. thnx!Genip
Have a look at developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…Freeboard
B
209

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.

Baese answered 22/2, 2012 at 14:24 Comment(6)
Bonus points for prototype chain. Still trying to figure out what its calling on when its not called on an object... its not windowPensioner
@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.Baese
I suppose that changes things. No error when run from console in Chrome though.Pensioner
@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.Baese
@KristofferSHansen see Kunal Vashist answer when it is called on a class methodGenip
@scubaFLY my comment was based on the original question where it wasn't used as a class method.Pensioner
O
48

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!

Obstacle answered 26/9, 2017 at 11:28 Comment(2)
at last line of your example you write console.log(Object.prototype....; did you mean console.log(fruitObject.? fruitObject or Object ?Depolymerize
>"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?Saintsimon
N
16

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
Nacreous answered 22/2, 2012 at 14:20 Comment(2)
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.Overwrought
@amnotiam- but i think its much clear now...its because my internet issue i cannot able to post more..........Nacreous
N
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]);
  }
}
Nitrogenous answered 17/8, 2018 at 15:31 Comment(0)
S
4

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.

Schriever answered 22/2, 2012 at 14:45 Comment(0)
M
4

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

Manful answered 4/5, 2020 at 17:21 Comment(0)
P
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
    }
}
Phalanger answered 22/2, 2012 at 14:28 Comment(0)
D
1

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

Devisal answered 31/10, 2021 at 7:49 Comment(0)
Z
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().

Zofiazoha answered 11/6, 2022 at 5:2 Comment(0)
A
0

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])
  }
}
Afghanistan answered 16/1, 2020 at 8:10 Comment(0)
B
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

Biotope answered 15/11, 2023 at 10:17 Comment(0)
E
-2

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

Eelpout answered 22/2, 2012 at 14:24 Comment(2)
obj.prop follows the prototype chain, hasOwnProperty does notPensioner
The problem is when prop has false value. if(obj.hasOwnProperty('prop')) will be true while if(obj.prop) will be false.Giavani

© 2022 - 2024 — McMap. All rights reserved.