Check if object has any property javascript

Object.prototype.hasOwnProperty()

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

Note: Object.hasOwn() is recommended over hasOwnProperty() , in browsers where it is supported.

Try it

Syntax

Parameters

The String name or Symbol of the property to test.

Return value

Returns true if the object has the specified property as own property; false otherwise.

Description

The hasOwnProperty() method returns true if the specified property is a direct property of the object — even if the value is null or undefined . The method returns false if the property is inherited, or has not been declared at all. Unlike the in operator, this method does not check for the specified property in the object’s prototype chain.

The method can be called on most JavaScript objects, because most objects descend from Object , and hence inherit its methods. For example Array is an Object , so you can use hasOwnProperty() method to check whether an index exists:

const fruits = ["Apple", "Banana", "Watermelon", "Orange"]; fruits.hasOwnProperty(3); // true ('Orange') fruits.hasOwnProperty(4); // false - not defined 

The method will not be available in objects where it is reimplemented, or on objects created using Object.create(null) (as these don’t inherit from Object.prototype ). Examples for these cases are given below.

Читайте также:  Cfg пингвин css v34

Examples

Using hasOwnProperty to test for an own property’s existence

The following code shows how to determine whether the example object contains a property named prop .

const example = >; example.hasOwnProperty("prop"); // false example.prop = "exists"; example.hasOwnProperty("prop"); // true - 'prop' has been defined example.prop = null; example.hasOwnProperty("prop"); // true - own property exists with value of null example.prop = undefined; example.hasOwnProperty("prop"); // true - own property exists with value of undefined 

Direct vs. inherited properties

The following example differentiates between direct properties and properties inherited through the prototype chain:

const example = >; example.prop = "exists"; // `hasOwnProperty` will only return true for direct properties: example.hasOwnProperty("prop"); // true example.hasOwnProperty("toString"); // false example.hasOwnProperty("hasOwnProperty"); // false // The `in` operator will return true for direct or inherited properties: "prop" in example; // true "toString" in example; // true "hasOwnProperty" in example; // true 

Iterating over the properties of an object

The following example shows how to iterate over the enumerable properties of an object without executing on inherited properties.

const buz =  fog: "stack", >; for (const name in buz)  if (buz.hasOwnProperty(name))  console.log(`this is fog ($name>) for sure. Value: $buz[name]>`); > else  console.log(name); // toString or something else > > 

Note that the for. in loop only iterates enumerable items: the absence of non-enumerable properties emitted from the loop does not imply that hasOwnProperty itself is confined strictly to enumerable items (as with Object.getOwnPropertyNames() ).

Using hasOwnProperty as a property name

JavaScript does not protect the property name hasOwnProperty ; an object that has a property with this name may return incorrect results:

const foo =  hasOwnProperty()  return false; >, bar: "Here be dragons", >; foo.hasOwnProperty("bar"); // re-implementation always returns false 

The recommended way to overcome this problem is to instead use Object.hasOwn() (in browsers that support it). Other alternatives include using an external hasOwnProperty :

const foo =  bar: "Here be dragons" >; // Use Object.hasOwn() method - recommended Object.hasOwn(foo, "bar"); // true // Use the hasOwnProperty property from the Object prototype Object.prototype.hasOwnProperty.call(foo, "bar"); // true // Use another Object's hasOwnProperty // and call it with 'this' set to foo (>).hasOwnProperty.call(foo, "bar"); // true 

Note that in the first two cases there are no newly created objects.

Objects created with Object.create(null)

Objects created using Object.create(null) do not inherit from Object.prototype , making hasOwnProperty() inaccessible.

const foo = Object.create(null); foo.prop = "exists"; foo.hasOwnProperty("prop"); // Uncaught TypeError: foo.hasOwnProperty is not a function 

The solutions in this case are the same as for the previous section: use Object.hasOwn() by preference, otherwise use an external object’s hasOwnProperty() .

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on May 1, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

How to Check if a Property Exists in a JavaScript Object

How to Check if a Property Exists in a JavaScript Object

When you are working with objects in JavaScript, you might need to check if a specific property exists or not.

In this article, I will show you three ways to check if a property exists in a JavaScript object.

How to Use the hasOwnProperty() Method in JavaScript

The hasOwnProperty() method will check if an object contains a direct property and will return true or false if it exists or not.

In this first example, we have an object called developer with three properties:

If we wanted to check if the isEmployed property exists in the developer object, then we can use the hasOwnProperty() method, like this:

developer.hasOwnProperty("isEmployed")

This would return true because the property called isEmployed is a direct property of the developer object.

But what if we tried checking for a property called isPrototypeOf ?

developer.hasOwnProperty("isPrototypeOf")

This would return false because there is no direct property called isPrototypeOf on the developer object. But what do I mean by direct property?

Whenever you create an object in JavaScript, there is a built-in property called a prototype and the value is another object. That object will have its own prototype, and this is know as a prototype chain.

Screen-Shot-2022-04-23-at-6.47.02-PM

Our developer object has access to these other properties, like toString , and this is what is known as an inherited property.

The hasOwnProperty() method will only return true for direct properties and not inherited properties from the prototype chain.

How to Use the in Operator

Unlike the hasOwnProperty() method, the in operator will return true for both direct and inherited properties that exist in the object.

We can modify our earlier example to check if the country property exists in the developer object using the in operator.

This would return true because the country property is a direct property in the developer object.

We can also check if the toString property exists on the developer object or in the prototype chain.

This would return true because the toString property does exist in the prototype chain because it was inherited from the prototype object.

How to Check if a Property Exists in an Object using undefined

If I tried to access a property name in an object that does not exist, then I would get undefined.

For example, if I tried developer.age then the return value would be undefined because the developer object does not have that property name.

We can check if a property exists in the object by checking if property !== undefined .

In this example, it would return true because the name property does exist in the developer object.

Conclusion

If you need to check if a property exists in a JavaScript object, then there are three common ways to do that.

The hasOwnProperty() method will check if an object contains a direct property and will return true or false if it exists or not. The hasOwnProperty() method will only return true for direct properties and not inherited properties from the prototype chain.

Unlike the hasOwnProperty() method, the in operator will return true for both direct and inherited properties that exist in the object or its prototype chain.

Lastly, we can see if a property exists in the object by checking if property !== undefined .

I hope you enjoyed this article and best of luck on your developer journey.

Источник

3 Ways to Check if an Object Has a Property in JavaScript

There are various ways to check if an object has a property in JavaScript. Before we start forward, let’s look at what it exactly means. An object is a compilation of unordered properties. Every Javascript object has some properties associated with it. A property of an object is a variable that binds to it. It can be modified or added or deleted, depending on the scenario.

How to check if an object has a property in JavaScript?

In this article, we will work on ways to check whether or not a property exists for an object in JavaScript with examples.

Method 1: Using hasOwnProperty() method

Let us have a look at the syntax of the method.

hasOwnProperty() :The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property.

prop: Property name that we want to check.

const JavaScript = < type: 'Language' >; console.log(JavaScript.hasOwnProperty('name')); console.log(JavaScript.hasOwnProperty('type'));

The above code creates an object called ‘ JavaScript ‘. The values mentioned in the curly braces are the respective properties and their values. So when we invoke the hasOwnProperty method on the object, it checks for the matching values. If present, hasOwnProperty() method returns true otherwise it returns false .

*Fact check: There are inherited properties with all objects. This method does not detect them. For example – toString , toLocaleString property

const JavaScript = < type: 'Language' >; console.log(JavaScript.hasOwnProperty('type'));// True console.log(JavaScript.hasOwnProperty('toLocaleString')); // => false

Method 2: Using the in operator

The in operator works similar to the above-discussed solution. The only difference is that the ‘ in ‘ operator can access the object’s inherited properties also. It is a syntactically better approach and also a short syntax compared to hasOwnProperty() .

Let us take an example to demonstrate in operator

const JavaScript = < type: 'Language' >; console.log('name' in JavaScript); console.log('type' in JavaScript ); console.log('toLocaleString' in JavaScript );

Method 3: Checking undefined value

This method requires no operator or function for evaluation. It uses the natural code syntax to perform the task.

The idea behind this approach is that we can compare with undefined to determine the existence of the property.

const JavaScript = < type: 'Language' >; JavaScript.type; // exist JavaScript.name;// does not exists let testVal = JavaScript.type !== undefined; console.log(testVal); // true let testVal = JavaScript.name !== undefined; console.log(testVal); // false

Comparing with undefined to match the value of a property is not a good approach. You may encounter a lot of false negatives. If the property is present having an undefined value, comparing it with the same gives a false negative.

const JavaScript = < type: undefined >; let testVal = JavaScript.name !== undefined; console.log(testVal); // false

But actually, the value exists.

Conclusion

To summarize, we have gone through 3 ways to check if an object has a property in JavaScript. The hasOwnProperty() is good and can evaluate an object but only in its scope. It does not consider the inherited or default properties. The in operator is a much better approach. It can detect all types of properties including inherited properties. It is much easier to apply in terms of syntax. The third method is not recommendable. We should compare the property with undefined to see if a property exists only when we are sure of the value.

Источник

Оцените статью