JavaScript check if object has property which is required for several reasons. The list is endless and includes validating data structures, preventing mistakes, examining dynamic attributes, creating conditional logic, optimizing, and enhancing performance.
In JavaScript, there are several methods to check if an object has a specific property, such as using the in operator, the object.hasOwn() and object.hasOwnProperty() methods, looking for undefined values, and many more.
In this JS article, we are going to discuss how to check if an object has a specific property or not. It’s a common task for every developer when they’re working with objects. This means we will cover every aspect of checking key existence within an object. So please bear with us.
Table of Contents
No. 1: JavaScript Check if Object Has Property Using In Operator
One of the most popular ways to check if an object has a property is by using the “in” operator. It is very easy to use and handy.
The JavaScript “in” operator returns true if the specified property is present within the object or in the prototype chain. It also works for the objects created with the Object.create() static method.
The in operator cannot be used to search for values in other collections except objects. If you would like to check if a certain value exists in an array, you should use the array.find() or array.findall() methods.
Syntax
prop in object
#prop in object
<script>
var student = { name: 'Student1', roll: 4036, year: 2022 };
console.log('name' in student);
// output: true
// Using In operator
// javascript check if object has property "name"
if ('name' in student) {
console.log('Property Exists.')
}
else{
console.log('Property Does Not Exists.')
}
</script>
Output: JavaScript Check if Object Has Property
More About In operator
The “in” operator checks if a property exists within an object or its prototype chain. If you don’t want to check the prototype chain, then using the “In” operator is not recommended. Use other JS methods, like hasOwn(), instead. We are going to discuss this method in a later part as well.
If a property value within an object is undefined, the in operator will always return true. If you want to make it false, then do not set the property value to undefined; rather, delete the property. Same for null, too.
<script>
var student = { name: 'Student1', roll: undefined, year: null };
console.log('roll' in student);
// output: true
console.log('year' in student);
// output: true
// javascript check if object has property
delete student.year;
// toString is an inherited property
// present in prototype chain
console.log(student.toString());
console.log('year' in student);
// output: false
console.log('toString' in student);
// output: true
</script>
We covered the cases of undefined, null, and prototype chains in our above example. If you like this example, please help us to grow. Share this article on your social platforms.
No. 2: Using hasOwnProperty() Method
JavaScript hasOwnProperty() method returns a boolean to indicate whether an obkect has the specified property or not.
Syntax
obj.hasOwnProperty(prop)
In the below example, JS hasOwnProperty() checks the presence of a specified property within an object.
<script>
var student = {
name: 'Student1',
roll: 4036,
year: 2022
};
// javascript check if object has property
var nameExist = student.hasOwnProperty('name');
if (nameExist) {
console.log('Name property exist, name: ' + student.name);
}
else {
console.log("Name property not exist!");
}
// Output: Name property exist, name: Student1
console.log(student.hasOwnProperty('age'));
// Output: false
// age property not exist within the object
</script>
More About hasOwnProperty() Method
The JS hasOwnProperty()
method returns a true value if and only if the specified property directly belongs to the object. Otherwise, this method will return false. Even if the specified property is an inherited property, the method will return false.
If the property value is null or undefined, the JavaScript hasOwnProperty()
method will return a true value.
<script>
var student = {};
console.log(student.hasOwnProperty('name')); // Output: false
student.name = 'Student1';
console.log(student.hasOwnProperty('name'));
// Output: true
// 'name' exists
// javascript check if object has property
student.name = null;
console.log(student.hasOwnProperty('name'));
// Output: true
// property exists with null value
student.name = undefined;
console.log(student.hasOwnProperty('name'));
// Output: true
// property exists but undefined
console.log(student.hasOwnProperty('toString'));
console.log(student.hasOwnProperty('hasOwnProperty'));
// Output: false
// property exists but in chain means inherited
var anotherStudent = Object.create({ name: 'Student2' });
console.log(anotherStudent.hasOwnProperty('name'));
// Output: false
// obj.hasOwnProperty() method does not works for objects
// created with Object.create() static method
</script>
Output
Difference Between In Operator & hasOwnProperty() Method
Both the in operator and hasOwnProperty() methods are almost similar and have similar functionalities to check if a specified object has a specific property or not. As discussed above, we are going to summarize the differences as well.
In Operator | hasOwnProperty() Method |
---|---|
Check if an object has a specific property directly or in the prototype chain. It means it can check inherited properties as well. | Check if an object has a specific property directly or not. Always return false for inherited properties. |
The operator works for the objects created with Object. create() static method. | This method does not work for objects created with the Object.create() static method. |
It’s a bit slow as this operator also checks the prototype chain. | A bit faster than In operator as this method does not check object prototype chain. |
Users do not prefer this method. | Users prefer this method to avoid issues with some keys, like constructors. |
No. 3: Using hasOwn() Method
The obj.hasOwn() static method returns true if the specified property directly exists within the object. But if the property is inherited or does not exist, the method returns false.
The obj.hasOwn() method is a new method and has not been supported by all browsers till now. But it’s recommended to use it over the hasOwnProperty() method because it also works for objects created by using Object.create(null) and for objects that have overridden the inherited hasOwnProperty() method.
Code Example
<script>
var student = {};
console.log(Object.hasOwn(student,'name')); // Output: false
student.name = 'Student1';
console.log(Object.hasOwn(student,'name'));
// Output: true
// 'name' exists
// javascript check if object has property
student.name = null;
console.log(Object.hasOwn(student,'name'));
// Output: true
// property exists with null value
student.name = undefined;
console.log(Object.hasOwn(student,'name'));
// Output: true
// property exists but undefined
console.log(Object.hasOwn(student,'toString'));
console.log(Object.hasOwn(student,'hasOwn'));
// Output: false
// property exists but in chain means inherited
var anotherStudent = Object.create({ name: 'Student2' });
console.log(Object.hasOwn(anotherStudent,'name'));
// Output: false
// obj.hasOwn() method does not works for objects
// created with Object.create() static method
</script>
Output
Difference Between hasOwn() & hasOwnProperty() Method
If you carefully examine the above two code examples and their outcome you can’t decide the differences between hasOwn() & hasOwnProperty() Method. But there are very few differences exists that we are going enlisted in the following table:
Object.hasOwn() | Obj.hasOwnProperty() |
---|---|
It’s a new method and not supported by all modern browsers. (Will be incorporated soon). | Supported by all legacy browsers. |
It’s recommend to use for modern browsers. | It’s not recommended to use for legacy support only. |
It works for objects created using Object.create(null). | It does not works for objects created using Object.create(null). |
Code Example to Check the Differences
<script>
let student = Object.create(null);
student.name = 'Student1';
console.log(Object.hasOwn(student, 'name'));
// Output: true
console.log(student.hasOwnProperty('name'));
// Return Error:
// Uncaught TypeError: student.hasOwnProperty is not a function
// javascript check if object has property
</script>
In the above code, a student object is created using the Object.create() method. Add the name property to check its existence later, followed by hasOwn and hasOwnProperty.
Based on the output, it’s clear to us that hasOwn worked correctly if an object was created by the Object.create() method, whereas the hasOwnProperty method gives a TypeError.
So based on our above discussion, we hope that the provided code examples are good enough to help us understand the tricky differences between these two JS methods. Right? So it’s time to explore the next method.
No. 4: Using Undefined Value
If a property does not exist within an object or the property value is set to undefined, then we receive an undefined error. So, we can use this technique to easily check the existence of a property within an object.
<script>
var student = {
name: 'Student1',
roll: 4036,
year: undefined
};
// javascript check if object has property age
// using undefined
if (student.age !== undefined) {
// Property exist
}
else {
console.log('age property is not exist in student object');
}
// Output: age property is not exist in student object
console.log(student.year !== undefined); // Output: false
</script>
student.age!== undefined returns false, which shows the property does not exist within the object student.
No. 5: Using Object.keys() and Array.some Method
In this approach, we are going to check the existence of the existence of a property within an object by using the Object.keys() and Array.prototype.some() methods.
This approach also has a similar issue with Object.prototype.hasOwnProperty() as an object created with Object.create() method always returns false.
<script>
var student = {
name: 'Student1',
roll: 4036,
year: 2022
};
var namePropExist = Object.keys(student).some(key => key === 'name');
console.log(namePropExist); // Output: true
var studentCpy = Object.create({ nickName: '........' });
var nickNameExist = Object.keys(studentCpy).some(Key => Key === 'nickName');
console.log(nickNameExist); // Output: false
</script>
In the above JS code block, first we convert the object to an array of properties, and then we have a method with a predicate function where we are checking the existence of the properties “name” and “nickName”.
No. 6: Using For Loop
JavaScript check if object has property: All built-in methods have been explained so far. Now we will try to manually define a method to check the existence of a the existence of a property within an object.
By using the for loop, we can iterate over every key of an object to check if a specific property exists. It’s an easy process but time consuming. Here is an example:
<script>
var student = {
name: 'Student1',
roll: 4036,
year: 2022
};
// javascript check if object has property
const student2 = Object.create({ name: 'Student2' });
function hasProp(obj, prop) {
if (obj && prop) {
for (const key in obj)
if (key === prop)
return true;
return false;
}
else {
return false;
}
}
console.log(hasProp(student, 'name')); // true
console.log(hasProp(student, 'age')); // false
console.log(hasProp(student2, 'name')); // true
</script>
hasProp() is a custom function that takes two arguments. One is the object, and the second is the required property name to check. Upon getting the object, a for loop is initiated to iterate over every key. Once the supplied property name is matched with the object key, return true, or else false at the end.
Conclusion
To explain “javascript check if object has property,” we have discussed almost every possible solution to chack a property presence within an object.
At first, we have explained the in operator. The method returns true if the specified property exists within the object or in the object prototype chain. Otherwise false.
The second way we mentioned is to use the object.hasOwnProperty(propName) method. The method returns true if the supplied property name directly exists within the object.
The difference between an operator and an object. hasOwnProperty(propName) method is also enlisted for your clear understanding.
The third way we mentioned is to use the hasOwn() method. This static method also returns true if the supplied property directly exists within the object like object.hasOwnProperty(propName) method. But there are some tricky differences between them, and we have also discussed those points.
Later on, we also discussed using an undefined value and how we can make a custom function to demonstrate how “javascript checks if an object has a property”.
Do you like this discussion? If yes, please promote us. Share our contents with your social media friends and help us grow together. Thanks.
FAQs on “javascript check if object has property”
What is the best method to check if a property exists in JavaScript?
Among those six particular methods, our strong recommendation is to use either the in operator or the hasOwn() method. Because the hasOwn() method is recommended by MDN over the hasOwnProperties() method, the in operator helps us check properties not only within the object but also within the prototype chain.
Is the JS Object.prototype.hasOwnProperty() method has been deprecated?
No, the hasOwnProperty() method is not deprecated yet. As per MDN, a replacement is included named the hasOwn() method, and this method is recommended for use with modern browsers only.
🏋️♂️ Discover Code Blocks From 20+ yrs JS Expert
💥 Asp.net C# Developer
🏆 Solution Architect
👨✈️ Database Administrator
📢 Speaker
🎓 MCTS since 2009
Leave a Reply