Table of Contents
Use Object.keys() method
grammar
Example
Use for-in loop
Use JSON.stringify() method
Home Web Front-end JS Tutorial How to check if an object is empty using JavaScript?

How to check if an object is empty using JavaScript?

Sep 14, 2023 pm 02:17 PM

如何使用 JavaScript 检查对象是否为空?

In JavaScript, objects are the most important data type and we need it most of the time when developing applications using JavaScript frameworks. Sometimes we need to check if an object is empty and perform operations based on the object value.

For example, you are getting data from the database; if it is not found, you can get an empty object. When you perform certain operations or perform certain methods on an empty object, it throws an error in your program. So it's better to check if the object is empty first.

We will learn three ways to check if an object is empty using JavaScript.

Use Object.keys() method

We can use the Object.keys() method to get the keys of objects in a single array. Afterwards, we can check the length of the array using its length property. If the length of the keys array is 0, it means that the object does not contain any keys and the object is empty.

grammar

Users can use the Object.keys() method according to the following syntax to check whether the object is empty.

let obj1Len = Object.keys(obj1).length;
if (obj1Len == 0) {
   
   // object is empty
} else {
   
   // object is not empty
} 
Copy after login

In the above syntax, Object.keys() returns an array of all keys of obj1, and we use the length property to get its length. Using the above syntax, we can get an array of all keys using the Object.keys() method, and we can also check the length of the array using the length property

Example

In the example below, we create two different objects. obj1 contains some properties, while obj2 is empty and does not contain any single property.

After that, we use the Object.keys() method on both objects to get the keys array and check the length of the array to make sure the object is empty or contains at least one property.

<html>
<body>
   <h3>Using the<i> object.keys() </i>method to check whether the object contains some value or not</h3>
   <p id = "output"> </p>
   <script>
      let output = document.getElementById("output");
      let obj1 = {
         prop1: 10,
         prop2: "Hi",
      };
      let obj2 = {};
      
      // get the array of all keys using the Object.keys() method,
      
      // check the length of the array using the length property
      let obj1Len = Object.keys(obj1).length;
      if (obj1Len != 0) {
         output.innerHTML += "The value of obj1 is " + JSON.stringify(obj1) + "</br>";
      } else {
         output.innerHTML += "The obj1 object is empty! </br>";
      }
      let obj2Len = Object.keys(obj2).length;
      if (obj2Len != 0) {
         output.innerHTML += "The value of obj1 is " + obj2 + "</br>";
      } else {
         output.innerHTML += "The obj2 object is empty! </br>"; 
      }
   </script>
</body>
</html>
Copy after login

Use for-in loop

for-in Loops allow us to iterate over the keys of an object. We can use for-in to loop through each key of the object. Here we will use for-in loop and check if it iterates over the object once, then the object contains at least one property and is not empty.

grammar

Users can use the for-in loop to check whether the object is empty according to the following syntax.

function isObjectEmpty(object) {
   for (ele in object) {
      
      // object is not empty
      return;
   }
   
   // if control comes here, the object is empty
} 
Copy after login

In the above syntax, if a single iteration of the for loop occurs, it means that we have ensured that the object contains at least one attribute. Therefore, we terminate the function using the return keyword after the first iteration of the for-in loop.

Example

In the example below, we create two different objects. Additionally, we created the isObjectEmpty() function that prints a different message depending on whether the object is empty or not.

We called the isObjectEmpty() function twice using different objects, and the user can observe its output.

<html>
<body>
   <h3>Using the <i>for-in loop</i> to check whether the object contains some value.</h3>
   <p id="output"></p>
   <script>
      let output = document.getElementById("output");
      
      // creating the objects
      let obj1 = {
         prop1: false,
      };
      let obj2 = {};
      
      // creating a function to check object is empty or not
      function isObjectEmpty(object) {
         for (ele in object) {
            
            // if any single iteration occurs using a for-in loop, it means the object contains at least one property
            output.innerHTML += "The object " + JSON.stringify(object) + " is not empty! </br>";
            return;
         }
         output.innerHTML += "The object " + JSON.stringify(object) + " is empty! </br>";
      }
      
      // calling the isObjectEmpty() function by passing different objects as an argument
      isObjectEmpty(obj1);
      isObjectEmpty(obj2);
   </script> 
</body>
</html>
Copy after login

Use JSON.stringify() method

JSON.stringify() method converts any value to the string we pass as the argument to the method. The syntax for an empty object is similar to {}, and the stringify() method always returns "{}" for an empty object.

Therefore, we can compare the return value of the stringify() method with "{}" to determine whether the object is empty.

grammar

Users can use the JSON.stringify() method according to the following syntax to check whether the object is empty.

if(JSON.stringify(education) == "{}") {
   
   // object is empty
} else {
   
   // object is not empty
}
Copy after login

In the above syntax, if the education object is empty, the JSON.stringify() method will return "{}".

Example

In the following example, we create the education object, which contains some properties. Therefore, the JSON.stringify() method will not return "{}", but will return the string value of the education object. Therefore, the user can observe the output showing that the education object is not empty.

<html>
<body> 
   <h3> Using the<i> JSON.stringify() method </i> to check whether object contains some value or not.</h3>
   <p id="output"></p>
   <script>
      let output = document.getElementById("output");
      
      // creating the objects
      let education = {
         totalYears: 12,
         school: "Online",
      };
      
      // convert object to string,
      
      // if object is empty, the JSON.stringify() method will return "{}"
      if (JSON.stringify(education) == "{}") {
         output.innerHTML += "Object is empty!";
      } else {
         output.innerHTML += "Education object is not empty!";
      }
   </script>
</body>
</html>
Copy after login

We learned three ways to check whether an object is empty. The first and third methods only require one line of code; the user needs to write 3 or 4 lines to use the second line. Therefore, it is better to use any one of the first and third methods for better code readability.

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

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

See all articles