JavaScript hasOwnProperty(): How to Use It Like a Pro

If you want to master JavaScript, you need to know how to work with objects and their properties. But sometimes, objects can behave in unexpected ways, causing bugs and confusion. That’s why you should learn how to use the JavaScript hasOwnProperty() method. This method helps you check if an object has a certain property as its own or if it inherited it from its prototype chain.In this blog post, we will explore:
  • What is hasOwnProperty()?
  • How to use hasOwnProperty() on simple objects, nested objects, and string-based property names
  • Leverage hasOwnProperty() on JavaScript’s Map object
  • Compare hasOwnProperty() vs in
  • Performance considerations with hasOwnProperty()
  • Troubleshooting hasOwnProperty() issues
Let’s dive deep.

What is hasOwnProperty() in JavaScript?

You can use the JavaScript hasOwnProperty() method to check if an object has a property with a given name. This function is helpful when you want to make sure that the property belongs to the object itself and not to its prototype chain. The hasOwnProperty() method lets you determine the source of the property more precisely.

Here is the hasOwnProperty() syntax:

object.hasOwnProperty(property)

How to use JavaScript hasOwnProperty()?

To illustrate hasOwnProperty() usage, let’s consider a basic example:

const person = {
  name: "John",
  age: 30,
};

console.log(person.hasOwnProperty("name")); 
// Output: true

console.log(person.hasOwnProperty("gender")); 
// Output: false
JavaScript hasOwnProperty()
JavaScript hasOwnProperty()

We use hasOwnProperty() to check if the "name" and "gender" properties exist in the "person" object. As expected, "name" is a property of the object, while "gender" is not.

Nested objects and hasOwnProperty()

The hasOwnProperty() function also works seamlessly with nested objects. Let’s see an example:

const company = {
  name: "ABC Corp",
  address: {
    street: "123 Main St",
    city: "New York",
  },
};

console.log(company.hasOwnProperty("address")); 
// Output: true

console.log(company.hasOwnProperty("street")); 
// Output: false

In the example above, we check if the address and street properties exist within the company object. As you can see, address is present, while street is not a direct property but a nested property within the address object.

Working with strings as property names

The hasOwnProperty() function also supports using JavaScript strings as property names. Consider the following example:

const person = {
  "Fist Name": "John",
  "age": 10,
};

console.log(person.hasOwnProperty("Fist Name")); 
// Output: true

console.log(person.hasOwnProperty("age")); 
// Output: true

We check for the existence of the properties "First Name" and "age" with string names in the "person" object using hasOwnProperty(). Both properties exist, as the output confirms.

Leveraging hasOwnProperty() with JavaScript's Map

You can also apply the hasOwnProperty() method to a Map() object in JavaScript. A Map() object is a non-primitive data type that stores key-value pairs.

To access the hasOwnProperty() method for an Map object, you have to convert the Map entries into an array using the entries() method. Then you can loop through the array and use hasOwnProperty() to verify if a key exists in the Map.

Here’s an example:

const myMap = new Map();
myMap.set('key1', 'value1');
myMap.set('key2', 'value2');
myMap.set('key3', 'value3');

const entries = Array.from(myMap.entries()); // Retrieve Map entries as an array

// Check if a key exists using hasOwnProperty()
console.log(entries.some(([key, value]) => Object.prototype.hasOwnProperty.call(myMap, key))); // true

// Check if a non-existent key exists
console.log(entries.some(([key, value]) => Object.prototype.hasOwnProperty.call(myMap, 'key4'))); // false

In the above example, we convert the Map entries to an array using Array.from() and store them in the entries variable. Then, we use the JavaScript some() method on the entries array to iterate over it. Inside the some() the callback function, we use Object.prototype.hasOwnProperty.call() to check if the Map object (myMap) has the specified key.

Understanding object ownership in JavaScript

In JavaScript, objects can have two types of properties: own properties and prototype properties. The object itself directly defines its own properties, but prototype properties come from the object’s prototype through inheritance.

The hasOwnProperty() method plays a crucial role in identifying own properties. Let’s understand this distinction with an example:

function Person(name) {
  this.name = name;
}

Person.prototype.age = 30;
const john = new Person("John");

console.log(john.hasOwnProperty("name")); 
// Output: true

console.log(john.hasOwnProperty("age")); 
// Output: false

In the example above, we create a Person constructor function and define a property called "name" on the object instance "john". Since "name" is an own property, hasOwnProperty() returns true.

However, the "age" property is inherited from the Person prototype, making it a prototype property and causing hasOwnProperty() to return false.

Comparing JavaScript hasOwnProperty() vs in operator

While hasOwnProperty() is ideal for checking own properties, JavaScript provides another operator called in that helps detect both own and inherited properties like toString().

Let’s compare in and hasOwnProperty():

const person = {
  name: "John",
};

console.log(person.hasOwnProperty("name")); // Output: true
console.log("name" in person); // Output: true

console.log(person.hasOwnProperty("toString")); // Output: false
console.log("toString" in person); // Output: true

It explains the difference between hasOwnProperty() and the in operator in terms of own and inherited properties.

To check if an object has a property that belongs to itself, not to its prototype chain, we use the hasOwnProperty() method. The in operator, on the other hand, checks if a property exists in an object or its prototype chain.

The choice between hasOwnProperty() and the in operator depends on whether you want to detect only your own properties or both your own and inherited properties.

JavaScript hasOwnProperty() performance considerations

While hasOwnProperty() is a powerful property checker, its potential impact on performance should be considered, especially when used in loops or frequently called functions.

Here are some tips to optimize performance:

  • Limit property checks to essential cases to minimize unnecessary operations.
  • Cache the hasOwnProperty() method for repeated use within a loop to avoid repeated lookups.
  • Consider alternative approaches that may offer better performance for specific scenarios.
JavaScript hasOwnProperty() vs in operator​ Performance Comparison
JavaScript hasOwnProperty() vs in operator​ Performance Comparison

I compared the speed of two operators: hasOwnProperty() and in. The in operator was slightly faster than hasOwnProperty(). With the in operator, I did 149,499 operations per second. With hasOwnProperty(), I did 148,295 operations per second. The in operator was faster by 0.81%.

Remember, optimizing performance should be based on the specific context and requirements of your application.

Checking for the presence of any property in a JavaScript Object

At times, you may need to determine if a JavaScript object has any properties at all. Here’s a generic function that accomplishes this:

function hasAnyProperties(object) {
  for (const prop in object) {
    if (object.hasOwnProperty(prop)) {
      return true;
    }
  }
    
  return false;
}

const person = {
  name: "John",
};

console.log(hasAnyProperties(person)); 
// Output: true

const emptyObject = {};
console.log(hasAnyProperties(emptyObject)); 
// Output: false

In the example above, the hasAnyProperties() function iterates over the object’s properties using a for...in loop and checks if any of the properties are its own. If at least one property is found, it returns true; otherwise, it returns false.

Troubleshooting JavaScript hasOwnProperty() issues

Sometimes, you may encounter issues while using hasOwnProperty(). Here are a few common pitfalls and how to troubleshoot them:
  • Ensure that you are calling hasOwnProperty() on the correct object instance.
  • Double-check the property name for typos or case sensitivity, as JavaScript is case-sensitive.
  • Be mindful of prototype properties that may overshadow your own properties, leading to unexpected results.
  • If hasOwnProperty() is not available on your target object (e.g., a map object), consider using alternate methods like Object.prototype.hasOwnProperty.call().

Exploring advanced usages of hasOwnProperty()

The hasOwnProperty() function can be applied to handle arrays and customized objects as well. Let’s explore some advanced scenarios:

Working with arrays

const titles = ["Javascript For Kids", "Effective Javascript", "Javascript Patterns"];

console.log(titles.hasOwnProperty("length")); // Output: true
console.log(titles.hasOwnProperty("0")); // Output: true
console.log(titles.hasOwnProperty("push")); // Output: false

In the example above, we use hasOwnProperty() to check properties like length and array indices (0) within an array. However, properties inherited from Array.prototype, such as push are not considered own properties.

Extending hasOwnProperty() for custom objects and classes

class Vehicle {
  constructor(make, model) {
    this.make = make;
    this.model = model;
  }
  
  hasOwn(property) {
    return Object.prototype.hasOwnProperty.call(this, property);
  }
}

const car = new Vehicle("Toyota", "Camry");

console.log(car.hasOwn("make")); // Output: true
console.log(car.hasOwn("year")); // Output: false

In this example, we extend the hasOwnProperty() functionality by adding a custom hasOwn method to the Vehicle class. By using Object.prototype.hasOwnProperty.call(), we ensure that the hasOwn method is called within the context of the current object instance.

Unique scenarios where hasOwnProperty() shines

The hasOwnProperty() function proves valuable in various unique scenarios. For instance, it can be used to validate user input, check for the existence of specific data properties, or validate the integrity of data structures.

Conclusion

We covered its usage in different scenarios, including nested objects, strings as property names, working with JavaScript’s Map object, and more. We also discussed performance considerations, troubleshooting tips, and advanced applications of hasOwnProperty().

By harnessing the power of JavaScript hasOwnProperty(), you can confidently navigate JavaScript objects, distinguish between own and inherited properties, and enhance the robustness and efficiency of your code.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Scroll to Top