This article will quickly explain how to check if an object is empty in JavaScript.
In daily JavaScript development, you may need to check if the object is empty. If you've ever done this, you probably know there is no single direct solution. However, you can use different techniques to create custom solutions that suit your own use cases. In addition, if you are using a JavaScript utility library in your project, the library may already provide a built-in way to check if the object is empty.
Modern Method (ES5)
In this section, we will discuss different methods you can use in modern browsers that support ES5 versions.
1. Object.keys()
method returns an array of enumeration attribute names of the given object. Therefore, we can check if the object has any properties by calculating the length of this array.
Let's look at the following example.
function isEmptyObject(obj) { return Object.keys(obj).length === 0; } console.log(isEmptyObject({})); // Output: true var bar = {"foo": "1"}; console.log(Object.keys(bar).length); // Output: 1 console.log(isEmptyObject(bar)); // Output: false
As shown in the above example, the foo
attribute is attached, so isEmptyObject
function will return the isEmptyObject
function with different values.
Note that isEmptyObject
will return true
for the RegExp object.
console.log(isEmptyObject(Date.now())); //Output: true console.log(isEmptyObject(new RegExp())); //Output: true
Also, be careful because this method is called with undefined values. They can cause exceptions. Later, we will create a bulletproof solution that does not fail on empty input.
console.log(isEmptyObject(null)); //Throw Uncaught TypeError: Cannot convert undefined or null to object
2. Object.getOwnPropertyNames()
method returns an array of all properties of the given object. Although it may look the same as Object.keys()
method, Object.getOwnPropertyNames()
method also considers non-enumerable properties, while Object.keys()
misses some properties declared non-enumerable.
Let's look at the following example.
function isEmptyObject(obj) { return Object.getOwnPropertyNames(obj).length === 0; } console.log(isEmptyObject({})); // Output: true var bar = {"foo": "1"}; console.log(Object.getOwnPropertyNames(bar).length); // Output: 1 console.log(isEmptyObject(bar)); // Output: false
As you can see, use Object.keys()
to test for null values.
However, the edge case is slightly different - Date
, but for null
or JSON.stringify
will return false
.
Use {}
to check if the given object is empty.
Let's look at the following example.
function isEmptyObject(obj){ return JSON.stringify(obj) === '{}'; } console.log(isEmptyObject({})); // Output: true var bar = {"foo":"1"}; console.log(JSON.stringify(bar)); // Output: {"foo":"1"} console.log(isEmptyObject(bar)); // Output: false
Again, the edge situation is slightly different. "1651283138454" is used in RegExp. So use the Object.getOwnPropertyNames
method!
console.log(isEmptyObject(Date.now())); //Output: false console.log(isEmptyObject(new RegExp())); //Output: true
Another change is false
, which may not be what you expect.
console.log(isEmptyObject(null)); //Output: false
4. Object.entries()
method returns an array of arrays, each element is an array of key-value pairs of object properties.
Let's look at the following example to understand how it works exactly.
function isEmptyObject(obj) { return Object.entries(obj).length === 0; } console.log(isEmptyObject({})); // Output: true var bar = {"foo":"1"}; console.log(Object.entries(bar)); // Output: [['foo', '1']] console.log(Object.entries(bar).length); // Output: 1 console.log(isEmptyObject(bar)); // Output: false
As you can see, Object.keys()
method will give the same result for our RegExp object edge case example. For undefined inputs, it also throws an exception.
console.log(isEmptyObject(Date.now())); //Output: true console.log(isEmptyObject(new RegExp())); //Output: true
Bulletproof Solutions
One problem with the simple solutions mentioned above is that they give inconsistent results for edge cases: special objects (such as Date), undefined values, or primitives (such as integers). This is a simple but more reliable solution.
function isEmptyObject(value) { const type = typeof value const isObject = value != null && type === 'object' return isObject && Object.keys(value).length === 0; }
This method is performed exactly by its name: it returns true
if and only if the input value is both an object and an empty object. It will work with null
and undefined
values - return false
because they are not objects. For special objects like RegExp, it will return true
because they do not define any special keys. It also returns true
for empty arrays and false
for non-empty arrays.
ES5 previous plan
In this section, we will discuss a solution that works even in older browsers. This method was often used before the JavaScript ES5 era, when there was no built-in method to check if an object was empty.
Let's look at the following example.
function isEmptyObject(obj) { for (var property in obj) { if (obj.hasOwnProperty(property)) { return false; } } return true; } console.log(isEmptyObject({})); // Output: true console.log(isEmptyObject({"foo":"1"})); // Output: false
In the example above, we built a custom function that you can call to check if the object is empty. It accepts a parameter, and you need to pass the object to test. In FALSE, otherwise we will return the isEmptyObject
function with a different value. As shown in the above example, we call it with a different value and record the output using the isEmptyObject
method, which allows you to check if the object is empty.
Let's take a quick look at the example below.
jQuery.isEmptyObject({}); // true jQuery.isEmptyObject({"foo":"1"}); // false
As you can see, using _.isEmpty()
is very simple.
in conclusion
In this article, we discuss several different ways to check if an object is empty in JavaScript. Check out our other tutorials on JavaScript programming!
This post has been updated with Neema Muganga’s contributions.
The above is the detailed content of How to Check if an Object Is Empty in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

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

SublimeText3 English version
Recommended: Win version, supports code prompts!

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Chinese version
Chinese version, very easy to use
