Home > Web Front-end > JS Tutorial > body text

How to check if an object exists in JavaScript?

王林
Release: 2023-09-02 14:33:02
forward
1330 people have browsed it

JavaScript 中如何检查对象是否存在?

This object contains properties and their values ​​in JavaScript. We can create an object using curly braces ({}). It is similar to a variable, but instead of assigning a number, string, or boolean value to the variable, we assign an object value.

So, in this tutorial, we will learn to check if an object exists in JavaScript. In short, we have to learn ways to check if an object variable exists.

Use try-catch statement

Usually, we use try-catch statements to handle errors in JavaScript. We can try to access the object or its properties in the try block and if the program does not find the object, it will throw an error and go to the catch block without completing the execution of the try block code.

grammar

Users can use the try-catch block according to the following syntax to check whether the object has been defined.

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

We are accessing undefined objects in the try block in the above syntax.

Example

In the following example, we use the try-catch statement. In the try block, we try to access the prop property of the object, which is undefined.

Users can observe in the output that execution control prints messages from the catch block, but does not print messages from the try block when accessing an undefined object, which will throw 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>
Copy after login

Use typeof operator

Developers can use the typeof operator to check the type of a variable. Here we will check if the variable type is equal to "Object" which means the object exists; otherwise if we get "undefined" or any other data type it means the variable is not of object type.

grammar

Users can use the typeof operator according to the following syntax to check whether the object exists.

let objType = typeof obj === ‘object’;
Copy after login

In the above syntax, the strict equality operator matches the return value of the typeof operator and the "object" string.

Example

In the following example, we create the obj object. When the user clicks the button, it calls the isObjectDefined() function. In the isObjectDefined() function, we use the typeof operator to get the type of obj variable and store it in objType. After that, we compare the value of objType variable with "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>
Copy after login

Use if-else statement

As we all know, we can pass conditions to if statements. The variable or object itself represents a Boolean value. When a variable exists and contains a value other than "null", it is indeed a Boolean value; otherwise, it is a false Boolean value. When we use a false boolean value as a condition for an if statement, control always goes to the else block.

grammar

Users can use if-else statements according to the following syntax to check whether the object exists.

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

In the above syntax, the object is the variable that contains the object.

Example

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

The user can observe the output of the if block where control goes when the 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>
Copy after login

Users learned three ways to check whether an object exists. Users can use any method according to their needs. If they also need to catch another error, they can use a try-catch block; otherwise, they use a normal if-else statement instead of the typeof operator.

The above is the detailed content of How to check if an object exists in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template