Javascript hasOwnProperty:  A Powerful Property Checking tool

Javascript hasOwnProperty: A Powerful Property Checking tool

Mastering JavaScript hasOwnProperty Method: Enhance Property Checks and Manipulations with Confidence

·

11 min read

Introduction

Javascript hasOwnProperty method is a built-in function in JavaScript that allows you to check whether an object has a specific property. This method is particularly important when you want to determine if a property exists directly on an object and not on its prototype chain(not inherited from its prototype).

This statement can be confusing. right?

Don't get panic, I am here to make you understand this in a very easy and efficient way.

In this article, we will explore the hasOwnProperty() method in detail, discussing its purpose and significance in property checking. We will deep dive into its syntax, purpose, and various scenarios where it can be applied.

By the end, you'll have a solid understanding of how to effectively utilize the hasOwnProperty() method in your JavaScript projects.

Prerequisites

Before diving into the concepts of javascript hasOwnProperty method, it's beneficial to have a basic understanding of JavaScript and its fundamental concepts. Familiarity with javascript variables, functions, and basic control flow (such as if statements and loops will make it easier to grasp the concepts discussed in this article.

If you're new to JavaScript or need a refresher, there are a few online resources available to learn the basics. Websites like MDN Web Docs, W3Schools, and freeCodeCamp offer comprehensive tutorials and guides that can help you get started on your JavaScript journey.

Additionally, I highly recommend the following two books for beginners in JavaScript:

By diving into these resources, you'll gain a solid foundation in JavaScript programming, equipping you with the necessary knowledge to explore the intricacies of hasOwnProperty and unlock new possibilities in your web development projects.

So, before we dive into the intricacies of javascript hasOwnProperty, make sure you have a solid foundation in JavaScript programming.

Once you're ready, let's explore the power of hasOwnProperty method and unlock new possibilities in your web development projects.

Syntax and parameters

To effectively utilize the JavaScript hasOwnProperty method, the First thing we need to do is getting know its syntax and get used to it by understanding its syntax and parameters in detail.

let's explore the syntax of it.

Note: If you find the syntax confusing, don't worry! In the upcoming sections of this article, we will explore various examples and use cases. I assure you that by reading the full article, you will gain a clear understanding of how to use hasOwnProperty() effectively. So, be patient and keep reading to unlock the full potential of this powerful JavaScript method.

The hasOwnProperty() method follows the following syntax:

object.hasOwnProperty(property)

Here,

  • object: This parameter represents the object on which the property check is performed. It can be any JavaScript object, including built-in objects, user-defined objects, or instances of classes.

  • property: This parameter specifies the name of the property being checked. It should be a string representing the property name.

  • return value: The hasOwnProperty() method returns a boolean value indicating whether the object has the specified property. It returns true if the object has the property, and false otherwise.

The hasOwnProperty() method returns true if the specified property is a direct property of the object — even if the value is null or undefined. The method returns false if the property is inherited, or has not been declared at all. Which we will discuss in later sections.

Working with hasOwnProperty()

Now we know the syntax of the javascript hasOwnProperty() method, let's look at an example of how to apply it in practical code.

let's consider an object called myObject:

 const person = {   name: 'John',   age: 30 }

To check if myObject has the property named name and gender, we would use the hasOwnProperty() method as follows:

console.log(person.hasOwnProperty('name')) // Output: true 
console.log(person.hasOwnProperty('gender')) // Output: false

In the above example, the person object has the properties name and age. The first console.log() statement checks if the object has the name property, and since the person object has the name property it returns true.

On the other hand, The second console.log() statement checks if the object has the gender property, and it returns false because the object does not have that property.

pretty straightforward. right?

Not really!

Handling inherited properties

In the previous section, we have seen that javascript hasOwnProperty method behaves in a very straightforward manner when we are checking for a property of the object.

But it works differently when we check for an inherited property of an object.

We know that In JavaScript, objects can inherit properties from their prototypes through the prototype chain. This inheritance behavior brings the importance of the hasOwnProperty() method into the spotlight, especially when dealing with inherited properties.

The hasOwnProperty() method ignores inherited properties. It focuses solely on the properties directly owned by the object itself.

When you invoke hasOwnProperty() on an object, it evaluates whether the object possesses a non-inherited property with the specified name. If such a property exists, the method returns true; otherwise, it returns false.

This method serves as a reliable indicator of whether an object has a specific property, regardless of its inheritance.

To clarify, consider the following example:

const person = {   name: 'John',   age: 30 }  
console.log(person.hasOwnProperty('name')) // Output: true
console.log(person.hasOwnProperty('toString')) // Output: false

In this example, we have an object called person with properties name and age. When we call hasOwnProperty() on the person object with name as the argument, it returns true since 'name' is a direct property owned by the object itself.

However, when we call hasOwnProperty() with toString as the argument, it returns false because toString is an inherited property from the object's prototype.

Purpose of hasownproperty()

At this point of this article after understanding the behavior of javascript hasOwnProperty, you might be thinking what is the purpose of it, more specifically why do we need it?

Purpose of hasownproperty()

Let's find out the answer. Probably you have heard the statement

everything is object in javascript.

What does it mean actually?

of course, we won't discuss its full explanation here.

In short, This means you can treat almost anything as an object in javascript. This includes numbers, strings, functions, and even arrays. And since almost anything can be treated as object, they also inherit properties from their parent objects through the prototype chain as an Object does.

That's why When working with objects, it can be challenging to differentiate between properties that are locally defined and those inherited from prototypes.

To address this, JavaScript provides the hasOwnProperty() method, which allows you to determine if a property exists directly on an object or is inherited from its prototype chain.

By using hasOwnProperty(), we ensure that we don't unintentionally modify any inherited properties or methods. It allows us to safely customize the behavior according to our requirements without affecting properties inherited from the prototype chain.

Here's an example to illustrate this:

const person = {
   name: 'John',   age: 30 
}  
if (person.hasOwnProperty('greet')) {
   person.greet = function () {
     console.log(`Hello, my name is ${this.name}`)   
  } 
}  

person.greet() // Output: Hello, my name is John

In this example, we have an object called person with properties like name and age. We want to customize the greet() method to provide a personalized greeting.

Using hasOwnProperty(), we check if the greet property already exists directly on the person object. If it does, we override the existing method with a new implementation that says Hello, my name is John In that way we are ensuring that we don't unintentionally modify inherited greed method in the person object.

Note: In some browsers where it is supported, Object.hasOwn() is recommended over hasOwnProperty().

hasOwnProperty() on Different JavaScript Objects

javascript hasOwnProperty method can be called on various JavaScript objects since most objects inherit its methods.

For example, let's consider the Array object. Since Array is an object itself, you can use the hasOwnProperty() method to check the existence of an index within the array:

const fruits = ['Apple', 'Banana', 'Watermelon', 'Orange'] 
console.log(fruits.hasOwnProperty(3)) // Output: true (corresponding to 'Orange') 
console.log(fruits.hasOwnProperty(4)) // Output: false (index not defined)

In this example, the fruits array contains several elements. By calling hasOwnProperty() on the array object with the argument 3, it returns true because the element at index 3 (Orange) exists within the array.

On the other hand, calling hasOwnProperty() with the argument 4 returns false because the array does not have an element at that index.

The ability to use hasOwnProperty() on arrays allows you to verify the presence of specific indices or elements within the array. It provides a convenient way to check the existence of array elements, ensuring that you access valid and defined values.

Objects where hasOwnProperty() is unavailable

Objects where hasOwnProperty() is unavailable

Although the javascript hasOwnProperty method is generally available in most JavaScript objects, there are certain cases where it may not be accessible.

hasOwnProperty as a property name

If an object redefines or overrides the hasOwnProperty() method, the original implementation from Object.prototype will not be available.

Here's an illustration of this scenario:

const customObj = {
   hasOwnProperty: function () {
     return 'Custom hasOwnProperty'  
   } 
}
customObj.hasOwnProperty('prop') // 'Custom hasOwnProperty'

In this case, the customObj object has its own implementation of hasOwnProperty(), which returns a custom message instead of the usual behavior.

As a result, when trying to call hasOwnProperty() on customObj, output will be the text(Custom hasOwnProperty) returned from the custom hasOwnProperty function.

Object created using Object.create(null)

Another scenario where hasOwnProperty() may not be accessible is when an object is created using Object.create(null). Objects created this way do not inherit from Object.prototype, and therefore do not have access to its methods, including hasOwnProperty().

Here's an example:

const foo = Object.create(null) 
foo.prop = 'exists' 
foo.hasOwnProperty('prop') // Error: foo.hasOwnProperty is not a function

In this case, foo is created using Object.create(null), which explicitly specifies that the object should not inherit from Object.prototype.

As a result, calling hasOwnProperty() on foo will throw an error because the method is not available.

Note: To handle these cases, you can use alternative approaches. One option is to use Object.hasOwn() method, which is a safer alternative that works even in situations where hasOwnProperty() may not be available.

Another option is to use hasOwnProperty() from another object that does inherit from Object.prototype, such as a plain {} object.

It's important to be aware of these scenarios and handle them accordingly to ensure your code functions as intended and avoids any unexpected errors or inconsistencies.

Handling non-object values

When the javascript hasOwnProperty method is invoked on non-object values, such as primitive data types or null, its behavior differs from when it is used on actual objects. It's important to understand these differences and the impact they have on property checks.

When hasOwnProperty() is called on a non-object value, the method will create a temporary wrapper object of the corresponding type and check for the existence of the property. If the property exists directly on the wrapper object, hasOwnProperty() will return true. Otherwise, it will return false.

Here's how hasOwnProperty() behaves with different types of values:

  • String Primitive:

      const name = 'John' 
      console.log(name.hasOwnProperty('length')) // Output: true
    

    In this case, the name variable is a string primitive. When hasOwnProperty() is called on it, JavaScript automatically converts it into a temporary String object. The String object has a property named length that it directly owns, so the method returns true.

  • Number Primitive:

      const age = 30 console.log(age.hasOwnProperty('toString')) // Output: false
    

    Here, the age variable is a number primitive. When hasOwnProperty() is called on it, it is converted into a temporary Number object.
    The Number object doesn't have a property named toString that it directly owns, so the method returns false.

  • Boolean Primitive:

      const isValid = true 
      console.log(isValid.hasOwnProperty('valueOf')) // Output: false
    

    In this example, the isValid variable is a boolean primitive. When hasOwnProperty() is called on it, it is converted into a temporary Boolean object. The Boolean object doesn't have a property named valueOf that it directly owns, so the method returns false.

  • Null and Undefined:

      let obj = null 
      console.log(obj.hasOwnProperty('property')) // Output: TypeError: Cannot convert null to object  let value 
      console.log(value.hasOwnProperty('property')) // Output: TypeError: Cannot convert undefined to object
    

    When hasOwnProperty() is called on null or undefined values, a TypeError is thrown. These values cannot be converted to objects, so invoking hasOwnProperty() directly on them results in an error.

It's important to be aware of how hasOwnProperty() behaves with different data types to ensure accurate property checks and handle any potential errors that may arise.

To avoid these errors, it is recommended to perform a type check before using the hasOwnProperty() method.

You can use the typeof operator to determine if the value is an object before calling hasOwnProperty().

For example:

const obj = { prop: 'value' } 
const str = 'Hello'  

if (typeof obj === 'object' && obj.hasOwnProperty('prop')) {           
    console.log("Object has own property 'prop'") 
}  

if (typeof str === 'object' && str.hasOwnProperty('length')) {  
    console.log("String has own property 'length'") 
} else {
   console.log("Value is not an object or does not have own property 'length'") 
}

In this example, we first check if obj is of type object and then use hasOwnProperty() to determine if it has the property prop.

Similarly, we perform the same check for str to verify if it is of type object and has the property length. If the conditions are met, the corresponding success message is logged.

Otherwise, if the value is not an object or doesn't have the expected property, an appropriate error message is displayed.

By performing the type check before calling hasOwnProperty(), you ensure that the method is only invoked on valid object values, mitigating any potential errors that could occur.

Conclusion

Javascript hasOwnProperty method is a useful tool for checking the existence of properties on objects. This provides more control and accuracy when performing property checks and manipulations.

Now that you have a solid understanding of hasOwnProperty(), you have a powerful tool at your disposal to handle property-related tasks with precision.

By leveraging this method, you can confidently work with object properties, tailor their behavior, and create more robust and reliable JavaScript applications.

Remember to practice and experiment with hasOwnProperty() to further deepen your understanding and proficiency. As you gain experience, you'll unlock its full potential and discover even more creative ways to enhance the functionality of your JavaScript applications.

Resource