# Javascript hasOwnProperty:  A Powerful Property Checking tool

## 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](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes)(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](https://robiul.dev/javascript-variables-beginner-thinking), functions, and basic control flow (such as if statements and [loops](https://robiul.dev/javascript-loop-best-practices-for-optimal-performance) 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript), [W3Schools](https://www.w3schools.com/js/), and [freeCodeCamp](https://www.freecodecamp.org/) 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:

* [Head First JavaScript Programming: A Brain-Friendly Guide](https://amzn.to/3IESIOn)
    
* [JavaScript: The Definitive Guide: Master the World's Most-Used Programming Language](https://amzn.to/3IGbjJN)
    

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:

```javascript
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:

```javascript
 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:

```javascript
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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain).

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:

```javascript
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()](https://cdn.hashnode.com/res/hashnode/image/upload/v1685023134668/68635a42-a099-4b1e-bc77-67378d92d80c.webp align="center")

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](https://blog.bitsrc.io/the-chronicles-of-javascript-objects-2d6b9205cd66#:~:text=Almost%20everything%20in%20JavaScript%20is,primitive%20values%20or%20primitive%20types.), 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:

```javascript
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:

```javascript
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](https://cdn.hashnode.com/res/hashnode/image/upload/v1685023078861/4a46a482-3431-465d-a838-0e9937bc12d9.webp align="center")

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:

```javascript
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)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create). 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:

```javascript
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`:
    
    ```javascript
    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`:
    
    ```javascript
    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`:
    
    ```javascript
    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`:
    
    ```javascript
    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:

```javascript
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

* [Object.prototype.hasOwnProperty()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty)
    
* [**Javascript hasownproperty method**](https://flexiple.com/javascript/hasownproperty-javacript/)
    
* [When to use Object.hasOwnProperty](https://idiallo.com/javascript/object-hasown-property-use-case-example)
    
* [Object.prototype.hasOwnProperty()](https://docs.w3cub.com/javascript/global_objects/object/hasownproperty)
