Бортовой журнал Ктулху

Как в javaScript проверить существование свойства | How to check if property exists in javaScript

Как проверить существование свойства в объектк js и избежать ошибки "Cannot Read Property of Undefined"?

qgSEu

const obj = {
name: "Pedro Homes",
age: 99,
address: {
street: "Av. Pdte. Ibáñez",
city: "Puerto Montt",
state: "Los lagos"
}
};

// Comparing with undefined
console.log(typeof obj.name)
console.log(typeof obj.sex)
// Check if "name" property exists in obj
if ("name" in obj) {
console.log("Property 'name' exists in obj");
}
// Check if "name" property exists in obj
if ("name" in obj) {
console.log("Property 'name' exists in obj");
}
// Check if "sex" property exists in obj
if ("sex" in obj) {
console.log("Property 'sex' exists in obj");
} else {
console.log("Property 'sex' does not exist in obj");
}
// if object has specified property
console.log(obj.hasOwnProperty('name')); // => true
console.log(obj.hasOwnProperty('sex')); // => false