Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript

What is the hasOwnProperty function in JavaScript?

Rukhshan Haroon

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The hasOwnProperty function in JavaScript is used to determine whether or not a particular property belongs to a predefined object.

Syntax

Object.hasOwnProperty(property)

Parameters

The hasOwnProperty takes in only one parameter:

  • property - the name of the property to check. Can either be of type Symbol or String.

Return value

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.

Example

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 person
const person = { fname: "John", lname: "Kent", age: 40};
console.log(person.hasOwnProperty('fname'));
// outputs true
console.log(person.hasOwnProperty('hasOwnProperty'));
// outputs false

RELATED TAGS

javascript

CONTRIBUTOR

Rukhshan Haroon
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring