Check if object has a specific property in JavaScript

You might need to check if a property exists in an object in case:

  • Validate the input data and avoid errors when accessing undefined properties.
  • Filter out the inherited properties and only work with the direct own properties.
  • Perform different actions based on the presence or absence of a property in an object.

There are different ways to check if a property exists in an object in JavaScript, depending on your use case and preference. Here are some of the common methods:

  • Using optional chaining and compare directly with undefined
  • Using hasOwnProperty() or Object.hasOwn()
  • Using in operator
  • Using Lodash _.has()

Using optional chaining

If your primary concern is checking whether a property exists in an object (regardless of its value being null or undefined), optional chaining alone is often sufficient.

Optional chaining handles the case where intermediate properties are null or undefined, gracefully returning undefined without throwing an error.

const user = {
  name: "John",
  address: {
    street: "123 Main St",
    city: "New York",
    // Uncomment the following line to test with a null or undefined value
    // city: null,
  },
};

// Using optional chaining to safely access nested properties
const cityName = user?.address?.city;

// Check if the city name exists and log the result
if (cityName !== undefined) {
  console.log(`The user lives in ${cityName}.`);
} else {
  console.log("City name not found.");
}

// Output:
// The user lives in New York.

Using hasOwnProperty()

If you specifically want to check whether a property is directly defined on the object (not inherited from its prototype chain), you may still use hasOwnProperty().

Optional chaining does not distinguish between own properties and inherited properties.

const person = { name: "Alice", age: 30 };

console.log(person.hasOwnProperty("name")); // true
console.log(person.hasOwnProperty("toString")); // false

But be careful when the object may not have the hasOwnProperty method itself, or when the method may have been overridden by a custom function. Suppose we have an object foo that is created with Object.create(null), which means it does not inherit from Object.prototype. If we try to use the hasOwnProperty() method, we will get an error:

const foo = Object.create(null);
foo.bar = "baz";
foo.hasOwnProperty("bar"); // TypeError: foo.hasOwnProperty is not a function

In this case you can use Object.prototype.hasOwnProperty.call() method or Object.hasOwn():

const foo = Object.create(null);
foo.bar = "baz";
Object.prototype.hasOwnProperty.call(foo, "bar"); // true

Using Object.hasOwn()

The new method Object.hasOwn() is a static method that returns true if the specified object has the specified property as its own property, and false otherwise. It is intended as a replacement for Object.prototype.hasOwnProperty(), which has some drawbacks and limitations.

If an object is created using Object.create(null), it does not inherit from Object.prototype, so it does not have the hasOwnProperty() method. In this case, you can use Object.hasOwn() to check for properties, but not hasOwnProperty().

let obj = Object.create(null);
obj.foo = "bar";

console.log(Object.hasOwn(obj, "foo")); // true
console.log(obj.hasOwnProperty("foo")); // TypeError: obj.hasOwnProperty is not a function

When an object overrides the inherited hasOwnProperty() method. In this case, the hasOwnProperty() method may not work as expected, but Object.hasOwn() will still work correctly.

let obj = {
  hasOwnProperty: function() {
    return false;
  },
  baz: 'qux'
};

console.log(Object.hasOwn(obj, 'baz')); // true
console.log(obj.hasOwnProperty('baz')); // false

It is recommended to use Object.hasOwn() over hasOwnProperty() as it is more reliable and intuitive.

Using in operator

The difference between hasOwnProperty() and in operator is that hasOwnProperty() only checks if the object itself has the property, while in operator checks if the property exists in the object or its prototype chain.

// Define an object with a name property
const user = {
  name: "Alice"
};

// Define another object that inherits from user
const admin = Object.create(user);
admin.role = "admin";

// Check if the name property exists using hasOwnProperty()
console.log(user.hasOwnProperty("name")); // true
console.log(admin.hasOwnProperty("name")); // false

// Check if the name property exists using in operator
console.log("name" in user); // true
console.log("name" in admin); // true

Using Lodash _.has()

Lodash _.has() is a method that checks if an object has a direct property with a given path. It is similar to the native JavaScript Object.hasOwn() method, checks only for direct properties, ignoring inherited ones.

It’s convenient for checking nested properties using dot notation _.has(obj, 'x.y.z'), useful for validating input data and avoiding errors when accessing undefined properties.

import _ from "lodash";

const user = {
  name: "Alice",
  age: 25,
  email: undefined,
  job: {
    name: "account",
    company: undefined,
  },
};

// direct properties
console.log(_.has(user, "name")); // true
console.log(_.has(user, "email")); // true
console.log(_.has(user, "phone")); // false

// nested properties
console.log(_.has(user, "job.name")); // true
console.log(_.has(user, "job.company")); // true
console.log(_.has(user, "job.x")); // false
console.log(_.has(user, "x.y.z")); // false

// inherited from Object.prototype
console.log(_.has(user, "toString")); // false