if (obj.hasOwnProperty('prop')) {
// do something
}
const object1 = new Object();
object1.property1 = 42;
console.log(object1.hasOwnProperty('property1'));
// expected output: true
const hero = {
name: 'Batman'
};
hero.hasOwnProperty('name'); // => true
hero.hasOwnProperty('realName'); // => false
const user1 = {
username: "john"
};
const user2 = {
username: "duo"
authority: "grepper"
}
// check object property
console.log(user1.hasOwnProperty('authority')); // false
console.log(user2.hasOwnProperty('authority')); // true
const userOne = {
name: 'Chris Bongers',
email: 'info@daily-dev-tips.com',
};
const userTwo = {
name: 'John Do',
};
console.log(userOne.hasOwnProperty('email'));
// Returns: true
console.log(userTwo.hasOwnProperty('email'));
// Returns: false
// the coolest way
const obj = {
weather: 'Sunny;
}
if('weather' in obj) {
// do something
}
const employee = {
id: 1,
name: "Jhon",
salary: 5000
};
const isSalaryExist = "salary" in employee;
console.log(isSalaryExist); //true
const isGenderExist = "gender" in employee;
console.log(isGenderExist); //false