The hasOwnProperty
function in JavaScript is used to determine whether or not a particular property belongs to a predefined object.
Object.hasOwnProperty(property)
The hasOwnProperty
takes in only one parameter:
property
- the name of the property to check. Can either be of type Symbol
or String
.The hasOwnProperty
function returns a boolean value. If the property belongs to the object being tested, true
is returned. Otherwise, false
is returned.
The function only returns true
if the property being tested is a direct property instead of an inherited one.
An inherited property is one that exists in the object’s prototype chain. A direct property is the object’s own property and does not belong to its prototype chain.
The function returns true
for undefined
or null
direct properties of the object as well.
The program below demonstrates how to use the hasOwnProperty
function. We declare an object named person
, which contains the first name, last name, and age of a person.
The hasOwnProperty
function is called twice. The first call checks whether or not the property fname
, which corresponds to the person’s first name, is a direct property of the object person
. true
is returned since fname
is a direct property of person
.
In the second call, the function checks whether or not the hasOwnProperty
method belongs to the object person
. Since it is an inherited property, the function returns false.
The return value is printed onto the console using the console.log
function:
// declare an object named personconst person = { fname: "John", lname: "Kent", age: 40};console.log(person.hasOwnProperty('fname'));// outputs trueconsole.log(person.hasOwnProperty('hasOwnProperty'));// outputs false