search
HomeWeb Front-endJS TutorialHow to check if an object is empty using JavaScript?

如何使用 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
} 

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 id="Using-the-i-object-keys-i-method-to-check-whether-the-object-contains-some-value-or-not">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>

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
} 

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 id="Using-the-i-for-in-loop-i-to-check-whether-the-object-contains-some-value">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>

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
}

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 id="Using-the-i-JSON-stringify-method-i-to-check-whether-object-contains-some-value-or-not"> 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>

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
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!