EN
JavaScript - check if object has key
0
points
In this article, we would like to show you how to check if object has certain key in JavaScript.
Quick solutions:
if (Object.prototype.hasOwnProperty.call(myObject, 'key')) {
// ...
}
or:
if ('key' in myObject) {
// ...
}
Warnings:
using
myObject.hasOwnProperty()construction may lead to mistakes by function overriding.
Incorrect code:if (myObject.hasOwnProperty('key')) { // ... }- it is more safe to use
hasOwnProperty()function thaninoperator.
Practical examples
1. Using hasOwnProperty() method
In this example we use hasOwnProperty() method to check if user object has age property.
// ONLINE-RUNNER:browser;
const user = { id: 1, name: 'Tom', age: 25 };
if (Object.prototype.hasOwnProperty.call(user, 'name')) {
console.log('The user object contains name property.');
}
Note:
This solution is safer than
inoperator.
2. Using in operator
In this example we use in operator to check if user object has age property.
// ONLINE-RUNNER:browser;
const user = { id: 1, name: 'Tom', age: 25 };
if ('name' in user) {
console.log('The user object contains name property.');
}
Warning:
The
inoperator matches all object keys, including those in the object's prototype chain.