Sunday, January 26, 2025
HomeProgrammingHow do I check if an object has a key in JavaScript?

How do I check if an object has a key in JavaScript?

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”);
}

See also  How can I use the AND statement in an if condition with JavaScript?

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.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x