To check if an object has a specific key in JavaScript, you can use the following methods:
1. in Operator:
Checks if the property exists in the object (including in its prototype chain).
if (‘key’ in object) {
console.log(“Key exists”);
}
2. hasOwnProperty() Method:
Checks if the property exists directly on the object, excluding the prototype chain.
if (object.hasOwnProperty(‘key’)) {
console.log(“Key exists”);
}
3. Object.hasOwn() Method (ES2022):
A modern alternative to hasOwnProperty().
if (Object.hasOwn(object, ‘key’)) {
console.log(“Key exists”);
}
Each method serves different use cases, with hasOwnProperty() and Object.hasOwn() being preferred for checking properties directly on the object.