Use the hasOwnProperty() Method in JavaScript Object - 04

The hasOwnProperty() method will check if an object contains a direct property and will return true or false if it exists or not. Here is the basic syntax:

obj.hasOwnProperty(prop)

let person = {
  name: "Mozahedul",
  title: "student",
  profession: "programmer"
}; console.log(person.hasOwnProperty("name"); // Return: true

Use the in operator:

Unlike the hasOwnProperty() method, the in operator will return true for both direct and inherited properties that exist in the object. Here is the basic syntax:
property in object
let person = {
  name: "Mozahedul",
  title: "student",
  profession: "programmer"
}; console.log("name" in person); // Return: true


Check the property in an Object using undefined:

We can check if a property exists in the object by checking if property !== undefined.
In this example, it would return true because the name property does exist in the developer object.

developer.name !== undefined


let person = {
  name: "Mozahedul",
  title: "student",
  profession: "programmer"
}; console.log(person.name !== undefined); // Return: true


Post a Comment

Previous Post Next Post