How to check whether an object exists in JavaScript?


The object contains the properties and their values in JavaScript. We can create an object using the curly ({}) braces. It’s similar to the variables, but we assign an object value rather than assigning the number, string, or boolean value to the variable.

So, here we will learn to check if the object exists in JavaScript in this tutorial. In short, we have to learn ways to check the existence of object variables.

Using the try-catch statement

Generally, we use the try-catch statement to handle errors in JavaScript. We can try to access the object or its properties in the try block, and if the program doesn’t find the object, it raises the error and goes to the catch block without completing the execution of the try block code.

Syntax

Users can follow the syntax below to use the try-catch block to check whether the object is defined.

try {
   let value = object.prop;
   // object is defined
} catch {
   // object is not defined
}

We access the undefined object in the try block in the above syntax.

Example

In the example below, we have used the try-catch statement. In the try block, we are trying to access the prop property of the object, which is not defined.

Users can observe in the output that execution control prints the message from the catch block but doesn’t print from the try block as we are accessing the undefined object, which will raise an error.

<html>
<body>
   <h3>Using the <i>try-catch block</i> to check if the object is defined in JavaScript.</h2>
   <p id = "output"> </p>
   <script>
      let output = document.getElementById("output");
      try {
         let value = object.prop;
         output.innerHTML += "The object is successfully defined!"
      } catch {
         output.innerHTML += "The object is not defined!"
      }
   </script>
</body>
</html>

Using the typeof operator

Developers can use the typeof operator to check the type of the variable. Here, we will check if the variable type is equal to the ‘object’, meaning the object exists; otherwise if we get ‘undefined’ or any other data type, that means the variable is not the object type.

Syntax

Users can follow the syntax below to check if the object exists using the typeof operator.

let objType = typeof obj === ‘object’;

In the above syntax, the strict equality operator matches the return value from the typeof operator and ‘object’ string.

Example

In the example below, we have created the obj object. When users click the button, it invokes the isObjectDefined() function. In the isObjectDefined() function, we used the typeof operator to get the type of the obj variable and stored it in the objType. After that, we compare the value of the objType variable with the ‘object’ to check if the object exists.

<html>
<body>
   <h2>Using the <i>typeof</i> operator to check if the object is defined in JavaScript.</h2>
   <p id = "output"></p>
   <button onclick = "isObjectDefined()"> Check for Object </button>
   <script>
      let output = document.getElementById("output");
      let obj = {
         prop1: "hello",
         prop2: "Users!"
      }
      function isObjectDefined() {
         let objType = typeof obj;
         if (objType === "object") {
            output.innerHTML += "The code contains the object!"
         } else {
            output.innerHTML += "The code doesn't contain the object!"
         }
      }
   </script>
</body>
</html>

Using the if-else statement

As you all know, we can pass the condition to the if statement. The variable or object itself represents the boolean value. When a variable exists and contains some value except ‘null’, it is truly a boolean value; Otherwise, it’s a false boolean value. Control always goes to the else block when we use the falsy boolean value as a condition of if-statement.

Syntax

Users can follow the syntax below to use the if-else statement to check if the object exists.

if (object) {
   // object exists
} else {
   // object doesn’t exist.
}

In the above syntax, the object is a variable containing the object.

Example

In the example below, we have created the phone object, which contains some properties and values as a key-value pair. After that, we used the if-else statement to check if the phone object exists in the code.

Users can observe the output that control goes to the if block as a phone object exists.

<html>
<body>
   <h2>Using the <i>if-else</i> statement to check if the object is defined in JavaScript.</h2>
   <p id = "output"> </p>
   <script>
      let output = document.getElementById("output");
      let phone = {
         "color": "blue",
         "RAM": "8GB",
         "ROM": "128GB"
      }
      if (phone) {
         output.innerHTML += "The phone object defined in the code!"
      } else {
         output.innerHTML += "The phone object isn't defined in the code!"
      }
   </script>
</body>
</html>

Users learned three approaches to checking if the object exists. Users can use any approach according to their requirements. If they also need to catch another error, they can use the try-catch block; otherwise, they use a normal if-else statement rather than the typeof operator.

Updated on: 19-Jan-2023

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements