Table of Contents Hide
Method 1: Using hasOwnProperty() method
Let us have a look at the syntax of the method.
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.
The above code creates an object called ‘
hasOwnProperty() method returns
true otherwise it returns
*Fact check: There are inherited properties with all objects. This method does not detect them. For example –
Method 2: Using the in operator
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
Let us take an example to demonstrate
false true true
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.
Let us see how it works.
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.
But actually, the value exists!!!!!
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.