if (obj.hasOwnProperty('prop')) {
// do something
}
const hero = {
name: 'Batman'
};
hero.hasOwnProperty('name'); // => true
hero.hasOwnProperty('realName'); // => false
myObj.hasOwnProperty(myProp)
let person = {
firstName: 'John',
lastName: 'Doe'
};
let result = 'firstName' in person;
console.log(result); // true
result = 'age' in person;
console.log(result); // false
Code language: JavaScript (javascript)
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
let result = person.hasOwnProperty('firstName');
console.log(result); // true
Code language: JavaScript (javascript)
// 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
let person = {
firstName: 'John',
lastName: 'Doe',
age: undefined
};
let result = person.age !== undefined;
console.log(result); // false
Code language: JavaScript (javascript)