How to Check If an Object is Empty in JavaScript [5 Ways]

Here are the five ways to check if an Object is empty in JavaScript.

  1. Using Object.keys()
  2. Using Object.values()
  3. Using for…in loop
  4. Using JSON.stringify
  5. Using Underscore and Lodash Libraries

Method 1: Using Object.keys()

Tthe Object.keys() method returns an array of the Object’s property names and checks if the length of the returned array is 0, which suggests that the Object has no properties.

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

const emptyObject = {};
const nonEmptyObject = { name: 'Niva Shah', age: 30 };

console.log(isEmptyObject(emptyObject));
console.log(isEmptyObject(nonEmptyObject));

Output

true
false

Method 2: Using Object.values()

You can also use the Object.values() method that returns an array of the Object’s values and checks if the length of the returned array is 0, which suggests that the Object has no values and is empty.

function isEmptyObject(obj) {
  return Object.values(obj).length === 0 && obj.constructor === Object;
}

const emptyObject = {};
const nonEmptyObject = { name: 'Niva Shah', age: 30 };

console.log(isEmptyObject(emptyObject));
console.log(isEmptyObject(nonEmptyObject));

Output

true
false

Method 3: Using for…in loop

This is a native way to check if an object is empty. You loop through the object, and if there’s at least one own property, it means the object isn’t empty.

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

obj = {}
console.log("If the object is empty: ", isEmpty(obj))

Output

If the object is empty: true

Method 4: Using JSON.stringify()

The JSON.stringify() method converts an object into a JSON string and checks if the string is equal to an empty object string.

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

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

obj = {}
console.log("If the object is empty: ", isEmpty(obj))

Output

If the object is empty: true

Method 5: Using Underscore and Lodash Libraries

const _ = require('lodash')

let obj = {};

let isEmpty = _.isEmpty(obj)

console.log("If the object is empty: ", isEmpty);

Output

If the object is empty: true

That’s it!