Javascript what is property in hasOwnProperty?

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

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

Why we can't 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?

Answers:

Answer

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.

Answer

Here is short and precise answer:

In javascript, every object has a bunch of built-in key-value pairs that have meta-information about 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 definetly don't want).

enter image description here

Using hasOwnPropery(property) filters-out these unnecessary looping through meta-informations and directly checks that is the parameter property is 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 !

Answer

it checks :

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

The hasOwnProperty method returns true if 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
Answer

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

Answer

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

object can have its own prototype, where 'default' methods and attributes are assigned to every instance of 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.

Answer

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

In your case somevar.hasOwnProperty('someProperty') it check the somevar function has somepropery or not ,, it return 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
}
}
Answer

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

Answer

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

Because JS doesn't protected the property of hasOwnProperty
So you can use like this

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

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

const someVar = { isFirst: false };


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


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

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.