JavaScript Obj.hasOwnProperty(prop) method
The obj.hasOwnProperty(prop)
method in JavaScript is used to determine whether a given object has a property as its own (not inherited) property. This method returns a boolean value: true
if the object has the specified property as its own property, and false
otherwise.
Syntax:
Parameters:
prop
: A string (or symbol) representing the name of the property to test for.
Return Value:
true
: If the object has the specified property as its own property.false
: If the property does not exist on the object or is inherited from its prototype chain.
Key Features:
- Own Properties vs. Inherited Properties: The
hasOwnProperty
method distinguishes between properties that are directly defined on the object and those that are inherited from the object's prototype. - Non-Enumerable Properties: The method can also be used to check for non-enumerable properties, which may not appear in loops like
for...in
. - Symbol Properties: It works with property names that are symbols, as well as strings.
Example 1: Basic Usage
In this example, hasOwnProperty
checks for the existence of the name
and age
properties, returning true
, while it returns false
for gender
since it is not defined on the object.
Example 2: Inherited Properties
Here, employee
has its own property position
, so hasOwnProperty('position')
returns true
. However, name
is inherited from person
, so hasOwnProperty('name')
returns false
.
Example 3: Checking Non-Enumerable Properties
In this example, prop
is defined as a non-enumerable property. While hasOwnProperty
returns true
, it does not appear in the for...in
loop.
Example 4: Using with Symbols
This example demonstrates that hasOwnProperty
can also be used with symbol properties, returning true
when checking for the presence of the symbol.
Summary:
obj.hasOwnProperty(prop)
is a method that checks whether the specified property exists as an own property of the object.- It distinguishes between properties defined directly on the object and those inherited from its prototype chain.
- This method is particularly useful in situations where you want to ensure that a property belongs directly to the object, avoiding unexpected results from inherited properties.