Check property existence in an object can be done with three main ways: [in] operator, hasOwnProperty method, or comparison with undefined value. Each way has its own features and is used in different situations.
Checking property existence is an important operation in JavaScript, especially when working with dynamic objects. There are several simple ways to do this.
Checks property existence in object and its prototypes:
const user = { name: 'John', age: 25 };
console.log('name' in user); // true
console.log('salary' in user); // falseChecks only object’s own properties:
const user = { name: 'John' };
console.log(user.hasOwnProperty('name')); // true
console.log(user.hasOwnProperty('toString')); // falseSimple way, but with pitfalls:
const user = { name: 'John', age: undefined };
console.log(user.name !== undefined); // true
console.log(user.age !== undefined); // false (though property exists!)// When need to check any property, including inherited
if ('toString' in user) {
// toString exists for all objects
}// When need to check only own properties
if (user.hasOwnProperty('name')) {
// Check only what we added
}// Simple case, but careful with undefined values
if (user.name !== undefined) {
// Works, but can deceive
}const user = { name: 'John' };
// Good - check before use
if ('age' in user) {
console.log(user.age);
} else {
console.log('Age not specified');
}const user = { name: 'John', age: 25 };
const field = 'name';
if (field in user) {
console.log(user[field]); // Safe access
}const obj = {};
console.log('toString' in obj); // true (inherited)
console.log(obj.hasOwnProperty('toString')); // false (not own)const obj = { value: undefined };
console.log('value' in obj); // true (property exists)
console.log(obj.value !== undefined); // false (but value is undefined)// ❌ Error - doesn't work with undefined values
const obj = { value: undefined };
if (obj.value !== undefined) {
console.log('Has value');
} else {
console.log('No value'); // Will trigger, though property exists!
}
// ✅ Correct - use in or hasOwnProperty
if ('value' in obj) {
console.log('Property exists'); // Correct result
}// ❌ May give unexpected result
const obj = {};
if ('toString' in obj) {
console.log('toString exists'); // Always true!
}
// ✅ Check only own properties
if (obj.hasOwnProperty('toString')) {
console.log('toString added by us');
} else {
console.log('toString inherited'); // Correct result
}Checking property existence helps write reliable code and avoid errors when working with objects.
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪