Check Keys Exist is exist in JavaScript Objects
There are two type of method to check if Keys Exist in JavaScript Objects, We Explain with code for better understanding.
Method 1: hasOwnProperty()
Using the hasOwnProperty() Method
The hasOwnProperty()
method returns a boolean value indicating whether the object has the specified property as its own property.
hasOwnProperty() method in JavaScript is used to check whether the object has the specified property as its own property. This is useful for checking if the object has inherited the property rather than being its own.
Syntax for Keys Exist in JavaScript Objects:
object.hasOwnProperty(prop)
Parameters:
- prop: It holds the name in the form of a String or a Symbol of the property to test.
Return Value:
It returns a Boolean value indicating whether the object has the given property as its own property.
Example:
const student = { name: 'John', age: 30, class:6 };
if (student.hasOwnProperty('age')) {
console.log('Property exists!');
} else {
console.log('Property does not exist.');
}
// Output: Property exists!
This method is often preferred when you need to ensure that the property is not inherited from the prototype chain.
Method 2: Using the ‘in’ Operator
Using the ‘in’ operator function
JavaScript ‘in’ operator is an inbuilt operator function which is used to tell whether a particular property is exist in an object or not. It returns a Boolean value true if the specified property is exist in an object, otherwise, it returns false.
prop in object
Parameters:
- prop: This parameter holds the string or symbol that represents a property name or array index.
- object: This parameter is an Object that is to be checked whether it contains the prop.
Return value:
This method returns a boolean value. The value true is returned if the specified property is found in an object, else it returns false.
Syntax:
if(key in object){
//code
}
Example:
const bike = { make: 'Honda', model: 'Shine' };
if ('make' in bike) {
console.log('Property exists!');
} else {
console.log('Property does not exist.');
}
// Output: Property exists!
Both the ‘hasOwnProperty’ operator and ‘in’ method are valuable property in a JavaScript developer’s toolkit.
This both are use to check spacific property is exist in an object or not