6 Ways to Check If an Object Has a Property/Key in JavaScript

Robin
Updated on September 16, 2022

Many times we check if a JavaScript object has a property or key to reduce the chance of getting unexpected errors. We also verify this to add properties in an object using JavaScript if they don't exist.

JavaScript has many methods like hasOwnProperty(), hasOwn(), or in operator to check if an object has a property or not. These methods accept a property name and compare it with the object. If they find a match return true otherwise return false.

Whatever the reason is you need to know how to check if a property exists in an object or not. You can easily confirm that using JavaScript.

In this article, we will look through different methods in JavaScript to confirm whether an object contains a property or not.

How to Check If an Object Has a Property in JavaScript

JavaScript has 6 different ways to check if an object has a property or key:

  • Check Property Name with hasOwnProperty() Method
  • Use hasOwn() Method to Check Object Property
  • Check If a Property Exists Using in Operator
  • Comparing The Property Name undefined
  • Check If a Property Exists Using Object.keys() Method
  • Check If a Property Exists With Object.entries() Method

Even though all of them can be used for this purpose, they have some differences. That's why you should know about those differences before using them in your project.

After knowing that properties exist, you can easily access object properties in JavaScript with various methods.

6 Ways to Check If an Object Has a Property/Key in JavaScript

Check Property Name with hasOwnProperty() Method

Every JavaScript object has access to the hasOwnProperty() method. It takes a string as a property name and returns a boolean value depending on whether that object contains the property or not.

          const person = {
    name: "James Smith",
    age: 37,
    gender: "male",
};

person.hasOwnProperty("name")
// true

person.hasOwnProperty("email")
// false

        

I have a person object which has 3 properties. When I call the hasOwnProperty() method on person object with the name property. I will return true because this object has this property.

But if I call this method with a property that doesn't exist, it will return false.

Note: You can also check methods of a JavaScript object using hasOwnProperty() method.

We know JavaScript objects inherit some properties and methods from their prototype chain. That's why we can call toString() method on every JavaScript object.

          person.toString()

person.hasOwnProperty("toString")
// false
        

But if you try to call the hasOwnProperty() method on the person object to check whether the toString() method exists or not, it will return false.

Because the hasOwnProperty() method can not identify the inherited properties and methods. It only looks into the own properties of an object i.e. the properties and methods that are defined directly inside the object.

Also Read: 6+ Ways to Find an Object in an Array of Objects Using JavaScript

Use hasOwn() Method to Check Object Property

The Object.hasOwn() method returns true if the property is declared directly in the object. Like hasOwnProperty() method, it also doesn't look into the object's prototype chain.

This method will return false if the property is inherited or has not been declared in the object.

          const person = {
    name: 'James Smith',
    age: 37,
    gender: 'male',
    email: 'james.smith@gmail.com',
};

Object.hasOwn(person, 'email')
// true

Object.hasOwn(person, 'address')
// false

        

You can't call the hasOwn() method on the object. Rather you have to call this method on the Object constructor. JavaScript uses this constructor function to create objects behind the scene.

The hasOwn() method accepts 2 arguments. The first argument is the actual object and the second argument is the name of the property that we want to check.

In this case, the property email is present in the person object so this method returns true. But the property address is not present therefore it returns false.

Initially, both hasOwnProperty() and hasOwn() methods might look the same. But it is recommended to use hasOwn() over hasOwnProperty() method.

Because we can use the hasOwn() method with the objects created using the Object.create(null) method. It also works with the objects whose hasOwnProperty() method is overridden.

Note: You can create a new object using an existing object in JavaScript with the Object.create() method.

          const person = Object.create(null);

person.name = 'James Smith';
person.age = 37;

Object.hasOwn(person, 'age')
// true


        

You can see when I try to check if the age property exists in the person object which is created using Object.create(null) method, it returns true.

But in this case, we can not call the hasOwnProperty() method on this person object.

          person.hasOwnProperty('name');
// TypeError: person.hasOwnProperty is not a function
        

Because when we create an object by passing null in the Object.create() method, the object will not have any inherited properties and methods.

That means, there is no hasOwnProperty() method in the person object. That's why it throws the TypeError.

Check If a Property Exists Using in Operator

JavaScript offers an in operator to verify if a property exists in an object. It is a very simple and short syntax compared to previous methods.

          const person = {
    name: 'James Smith',
    age: 37,
    gender: 'male',
    email: 'james.smith@gmail.com',
};

'email' in person;
// true

'address' in person;
// false

        

You have to place the in operator in between the property name and the object. It will return true if the property exists in the object otherwise it returns false.

The email in person gives true because email property is present in the person object. But we get false for the address property.

          'toString' in person
// true
        

The difference is that the in operator also looks into the inherited properties and methods. That's why it returns true when we try to detect whether the toString is present in the person object or not.

Also Read: In-Depth Guide to Shuffle Any Type of JavaScript Array

Comparing The Property Name undefined

We can identify the non-existing properties by comparing their names with undefined. Because when we access the property name that exists, it will return the property value.

But when we access the property name that doesn't exist in the object, we will get undefined as the return value.

          const person = {
    name: 'James Smith',
    age: 37,
    gender: 'male',
    email: 'james.smith@gmail.com',
};

person.name
// 'James Smith'

person.address
// undefined

        

We can use this characteristic to check if an object has a property or key. For that, we will make use of the !== (not equal) syntax.

          const person = {
    name: 'James Smith',
    age: 37,
    gender: 'male',
    email: 'james.smith@gmail.com',
};

person.name !== undefined
// true

person.address !== undefined
// false

        

The name property is not equal to undefined that's why person.name !== undefined returns true. Therefore, it confirms that the name property exists in the person object.

On the other hand, person.address !== undefined is false because person.address is equal to undefined. That means, person object doesn't contain the address property.

But if the property value is undefined then this technique will not work.

          const person = {
    name: undefined,
    age: 37,
    gender: 'male',
    email: 'james.smith@gmail.com',
};

person.name !== undefined
// false

        

In this object, the value of name property is undefined. Therefore, when we try to check this property with person.name !== undefined syntax, it will return false.

As you can see, it is giving the wrong result. Even though the name property exits, this will show as if it does not. In this case, you can use the Object.hasOwn() method.

Check If a Property Exists Using Object.keys() Method

We can verify if a property is present in an object by looping through the object in JavaScript using Object.keys method.

The Object.keys() method accepts an object as its argument and returns an array with all its property names. Therefore, we can check if our property name is present in that array or not.

          const person = {
    name: 'James Smith',
    age: 37,
    gender: 'male',
    email: 'james.smith@gmail.com',
};

const keys = Object.keys(person);
// [ 'name', 'age', 'gender', 'email' ]

keys.includes('name')
// true

keys.includes('address')
// false

        

I am passing the parson object in the Object.keys() method. I am storing the array of properties in the keys variable. Now I can check a property name using includes() array method.

This method is returning true because the name property is present in the keys array. But for address it is giving false.

          const person = {
    name: 'James Smith',
    age: 37,
    gender: 'male',
    email: 'james.smith@gmail.com',
};

const person2 = Object.create(person);

person2.username = 'john123';

const keys2 = Object.keys(person2);

console.log(keys2);
// ['username']

        

When we create one object from another object using Object.create() method, the Object.keys() method doesn't return the inherited properties.

I am creating the person2 object from the person object. Then I added the username property on the person2 object.

When I get the properties from the person2 object using Object.keys() method, I am only getting an array with the username property. This time array doesn't contain the properties from the person object.

Check If a Property Exists With Object.entries() Method

There is a method called entries() on the Object constructor. Unlike Object.keys(), it returns an array that contains both properties and values of an object.

          const person = {
    name: 'James Smith',
    age: 37,
    gender: 'male',
    email: 'james.smith@gmail.com',
};

const items = Object.entries(person);
console.log(items);
        

Output:

          [
  [ 'name', 'James Smith' ],
  [ 'age', 37 ],
  [ 'gender', 'male' ],
  [ 'email', 'james.smith@gmail.com' ]
]
        

As you can see, when I call the Object. entries() method with the person object, it will return an array of arrays. Each inner array will have the property and value of that object.

Always the first item will be the name of the property and the second item will be the value of that property.

          let result = false;

for (const [key, value] of items) {
    if (key === 'age') {
        result = true;
        break;
    }
}

console.log(result)
// true
        

Now I can iterate over the items array using the for...of loop in JavaScript. I am destructuring the key and value from each item array in the loop. I have declared the result variable outside the loop whose initial value is false by default.

Inside the loop, I am checking if the key is equal to age then I will re-assign the result value to true and break out from the loop using the break keyword.

You can check any property name in the if statement. By breaking out from the loop, I am making sure that the for...of loop doesn't iterate over every item unnecessarily.

Whenever I am getting a match, there is no need to check the rest of the items in the items array. In such conditions, you can break out of the loop and save some time.

Like Object.keys() method, Object.entries() method also doesn't return the inherited properties and values.

          const person2 = Object.create(person);

person2.username = 'john123';

const keys2 = Object.entries(person2);

console.log(keys2);
        

Output:

          [
     ['username', 'john123]
]
        

As you can see, after creating one object from another, the Object.entries() method only returning the property and value from the person2 object.

Also Read: Tricks to Loop Through an Array of Objects in JavaScript

Conclusion

Whenever you need to check if a property exists in an object, you can use any one of these 6 ways in JavaScript. Every technique has some specific characteristics. You can compare them with your requirements.

Like if you want to check a property name in an object along with its prototype chain, you can use the in operator. But if you don't want inherited properties and methods then you can choose other methods.

I hope it was helpful for you. Now you know how to check if an object has a property or key in JavaScript and you will be able to use this knowledge in the future.

Related Posts