How to check if a key or property exists in an object in JavaScript?

November 21, 2020 - 2 min read

To check if a key exists in an object, you can use the in operator in JavaScript.

Let's say we have a person object like this,

// an object
const person = {
  name: "John Doe",
  age: 23,
  isCustomer: true,
};

What if we want to check for key age in the person object?

Let's use the in operator to check like this,

// an object
const person = {
  name: "John Doe",
  age: 23,
  isCustomer: true,
};

// check if key age
// exists in person object
// using the "in" operator
if ("age" in person) {
  console.log("Key: age exists!", person.age);
} else {
  console.log("Key: age doesn't exists!");
}

See this example live in JSBin.

The in operator also checks to see if the key is present on inherited properties. If you don't want that and need to check only on the current instance of the object, you can use the hasOwnProperty() object method like this,

// an object
const person = {
  name: "John Doe",
  age: 23,
  isCustomer: true,
};

// check if key age exists
// but checks only the current
// instance of object and not
// inherited properties!"
if (person.hasOwnProperty("age")) {
  console.log(
    "Key: age exists, Checks only the current instance of object and not inherited properties!",
    person.age
  );
} else {
  console.log("Key: age doesn't exists!");
}

See this example live in JSBin.

Feel free to share if you found this useful 😃.