JavaScript: 3 Ways to Check if an Object is Empty

Updated: March 14, 2023 By: Khue Post a comment

This concise, straight-to-the-point article shows you a couple of different ways to check whether a given object is empty or not in JavaScript.

Using the Object.keys(), Object.values(), or Object.entries() method

One common approach is to use the Object.keys() method, which returns an array of the object’s own property names. You can then check if the length of this array is zero, which means the object has no keys and is empty.

Example:

const obj1 = {}
const obj2 = {name: 'Sling Academy'}

if(Object.keys(obj1).length === 0){
    console.log('obj1 is empty')
} else {
    console.log('obj1 is not empty')
}

if(Object.keys(obj2).length === 0){ 
    console.log('obj2 is empty')
} else {
    console.log('obj2 is not empty')
}

Output:

obj1 is empty
obj2 is not empt

Likewise, you can call Object.values() or Object.entries(), which return an array of the object’s own property values or key-value pairs, then examine the length of the resulting array.

Using JSON.stringify()

The JSON.stringify() method converts a JavaScript object into a JSON string. If an object is empty, the resulting string will be {}.

Example:

const isEmptyObject = (obj) => {
  return JSON.stringify(obj) === '{}';
};

// try it out
const obj = {};
console.log(isEmptyObject(obj)); 

Output:

true

Using a for…in loop

A for…in loop can be used to iterate over the object’s own and inherited enumerable properties. You can then use a flag variable to track if any property is found and break out of the loop as soon as one is found.

Example:

const user = {};
let isEmpty = true;
for (let key in user) {
  isEmpty = false;
  break;
}

console.log(isEmpty); 

Output:

true

That’s it. Goodbye!