Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to check if an object has a property in JavaScript

In this blog post, we're going to explore how to check if an object has a specific property in JavaScript. This is a common task when working with objects, and understanding how to perform this check can help you write better, more efficient code. We'll be covering the following topics:

  1. What is an object in JavaScript?
  2. What is a property?
  3. Different ways to check if an object has a property
  • The in operator
  • The hasOwnProperty() method
  • The Object.prototype.hasOwnProperty.call() method
  1. Use cases and examples

1. What is an object in JavaScript?

In JavaScript, an object is a collection of key-value pairs, where the key is a string and the value can be any data type, such as a number, string, or another object. You can think of an object as a container that holds different pieces of information, each with its own unique label. Here's an example of an object:

let person = {
  firstName: "John",
  lastName: "Doe",
  age: 30,
  hobbies: ["reading", "traveling", "coding"]
};

In this example, the person object has four properties: firstName, lastName, age, and hobbies. The values of these properties are a combination of strings, a number, and an array.

2. What is a property?

A property is a key-value pair in an object. In the person object example above, firstName, lastName, age, and hobbies are properties. Properties can be accessed using dot notation (e.g., person.firstName) or bracket notation (e.g., person["firstName"]).

3. Different ways to check if an object has a property

There are several ways to check if an object has a specific property in JavaScript. We'll discuss three popular methods: the in operator, the hasOwnProperty() method, and the Object.prototype.hasOwnProperty.call() method.

3.1 The in operator

The in operator is a simple way to check if an object has a specific property. It returns true if the object has the given property, and false otherwise. Here's an example using the person object from earlier:

console.log("firstName" in person); // true
console.log("email" in person); // false

The in operator checks not only if the object itself has the property, but also if the property is inherited from the object's prototype. In most cases, this is not a problem. However, if you need to check if the object itself has the property (and not its prototype), you should use the hasOwnProperty() method instead.

3.2 The hasOwnProperty() method

The hasOwnProperty() method is a built-in JavaScript method that checks if an object has a specific property as its own property (i.e., not inherited from the object's prototype). It returns true if the object has the property, and false otherwise.

Here's an example using the person object:

console.log(person.hasOwnProperty("firstName")); // true
console.log(person.hasOwnProperty("email")); // false

The hasOwnProperty() method is a more precise way to check if an object has a property compared to the in operator because it only checks if the object itself has the property, not its prototype.

3.3 The Object.prototype.hasOwnProperty.call() method

In some cases, you might be working with an object that doesn't inherit from the standard JavaScript Object.prototype. In these situations, you can't use the hasOwnProperty() method directly on the object, because it's not part of the object's prototype chain. Instead, you can use the Object.prototype.hasOwnProperty.call() method.

Here's an example:

let obj = Object.create(null);
obj.name = "Alice";

console.log(Object.prototype.hasOwnProperty.call(obj, "name")); // true
console.log(Object.prototype.hasOwnProperty.call(obj, "email")); // false

In this example, we create an object called obj using Object.create(null), which creates an object without inheriting from the standard JavaScript Object.prototype. This means that obj doesn't have the hasOwnProperty() method. However, we can still check if obj has a specific property using the Object.prototype.hasOwnProperty.call() method.

4. Use cases and examples

Let's look at some practical examples of how to check if an object has a property using the methods we discussed.

4.1 Checking if an object has a property before accessing it

One common use case for checking if an object has a property is to avoid errors when trying to access the property's value. For example, let's say you have an object representing a user, and you want to display the user's email address if it exists. You can use the in operator or the hasOwnProperty() method to check if the email property exists before trying to access its value:

let user = {
  name: "Jane",
  age: 25
};

if ("email" in user) {
  console.log("User's email:", user.email);
} else {
  console.log("User's email not available");
}

4.2 Checking for optional properties in function arguments

When writing a function that accepts an object as an argument, you might want to check if the object has certain optional properties. For example, let's say you have a function that calculates the total price of an order, and the order object may or may not have a discount property:

function calculateTotalPrice(order) {
  let total = order.price * order.quantity;

  if (order.hasOwnProperty("discount")) {
    total -= order.discount;
  }

  return total;
}

let order1 = {
  price: 10,
  quantity: 3,
  discount: 5
};

let order2 = {
  price: 15,
  quantity: 2
};

console.log(calculateTotalPrice(order1)); // 25
console.log(calculateTotalPrice(order2)); // 30

In this example, the calculateTotalPrice() function checks if the order object has the discount property using the hasOwnProperty() method before applying the discount to the total price.

Conclusion

In this blog post, we discussed how to check if an object has a specific property in JavaScript using the in operator, the hasOwnProperty() method, and the Object.prototype.hasOwnProperty.call() method. Knowing how to perform this check is essential for working with objects in JavaScript and can help you write more efficient and error-free code.

Remember to choose the appropriate method based on your specific needs. Use the in operator if you want to check if the object has the property or if the property is inherited from the object's prototype. Use the hasOwnProperty() method if you need to check if the object itself has the property (and not its prototype). Finally, use the Object.prototype.hasOwnProperty.call() method if you're working with an object that doesn't inherit from the standard JavaScript Object.prototype.