How do you check if an object has a property in JavaScript?

You can check if an object has a property in JavaScript using the hasOwnProperty() method or the in operator.

  1. hasOwnProperty() method:

    This method returns a boolean value indicating whether the object has the specified property as its own property (not inherited from its prototype chain).

    Here is an example:

    const obj = { name: "John", age: 30 };
    console.log(obj.hasOwnProperty("name")); // true
    console.log(obj.hasOwnProperty("gender")); // false
  2. in operator:

    This operator returns a boolean value indicating whether the specified property exists in the object, including properties inherited from its prototype chain.

    Here is an example:

    const obj = { name: "John", age: 30 };
    console.log("name" in obj); // true
    console.log("gender" in obj); // false

    Note that the in operator can also be used to check if an object has an index in an array or a key in a map.

Thank you for reading, and let’s have conversation with each other

Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.

Read more: