How to Check If an Object Is Empty in JavaScript

Here are five quick and easy ways to check if an object is empty in JavaScript.

Written by K. Jagathish
How to Check If an Object Is Empty in JavaScript
Image: Shutterstock / Built In
Brand Studio Logo
UPDATED BY
Hal Koss | Jul 22, 2024

In this article you will learn five different ways to check if an object is empty in JavaScript. Let’s jump right in.

How to Check If an Object Is Empty in JavaScript

  1. Use Object.keys
  2. Loop Over Object Properties With for…in
  3. Use JSON.stringify
  4. Use jQuery
  5. Use Underscore and Lodash Libraries

 

1. Use Object.keys

Object.keys will return an array, which contains the property names of the object. If the length of the array is 0, then we know that the object is empty.

function isEmpty(obj) {
    return **Object.keys(obj).length === 0**;
}

We can also check this using Object.values and Object.entries. This is typically the easiest way to determine if an object is empty.

More From Built In ExpertsFauna: An Introduction

 

2. Loop Over Object Properties With for…in

The for…in statement will loop through the enumerable property of the object.

function isEmpty(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return false;
    }
    return true;
}

In the above code, we will loop through object properties and if an object has at least one property, then it will enter the loop and return false. If the object doesn’t have any properties then it will return true.

Tutorials for Software Developers on Built InCreate React App and TypeScript — A Quick How-To

 

3. Use JSON.stringify

If we stringify the object and the result is simply an opening and closing bracket, we know the object is empty.

function isEmptyObject(obj){
    return JSON.stringify(obj) === '{}'
}

 

4. Use jQuery

jQuery.isEmptyObject(obj); 

Related ReadingWhat Is the @ Symbol in Python and How Do I Use It?

 

5. Use Underscore and Lodash Libraries

_.isEmpty(obj);

These five quick and easy ways to check if an object is empty in JavaScript are all you need to get going.

Hiring Now
Anduril
Aerospace • Artificial Intelligence • Hardware • Robotics • Security • Software • Defense
SHARE