Check if an object is empty in JavaScript

OpenJavaScript 0

Last updated: November 27, 2023.

Want to know if an object is empty?

With an array you can do this by checking the value of its length property. But this is not possible with an object:

/* Checking if array is empty */
const array = [];
console.log(array.length); // 0

const arrayIsEmpty = array.length === 0;
console.log(arrayIsEmpty); // true

/* Checking if object is empty */
const obj = {};
console.log(obj.length); // undefined

const objIsEmpty = obj.length === 0;
console.log(objIsEmpty); // false

The problem with the above code that leads to the incorrect result for the object is length property returns undefined (this will always be the result).

To get the correct result for an object, you can parse it into an array of its first-level keys using Object.keys():

/* Checking if object is empty by keys */
const obj = {};
const keysInObj = Object.keys(obj);

console.log(keysInObj); // []
console.log(keysInObj.length); // 0

const objIsEmpty = keysInObj.length === 0;
console.log(objIsEmpty); // true

Doing so does not affect the original object:

const obj = {};
const keysInObj = Object.keys(obj);

console.log(keysInObj); // []
console.log(obj); // {}

The code for testing whether an object is empty can be shortened to:

Object.keys(myObject).length === 0; // true or false

On larger projects where you want to perform the test multiple times, you may want to encapsulate the test into a reusable function:

const emptyObj = {};
const nonEmptyObj = { 
  firstName: "Nicolas",
  lastName: "Cage",
};

function objIsEmpty(inputObj) {
  return Object.keys(inputObj).length === 0;
}

console.log(objIsEmpty(emptyObj)); // true
console.log(objIsEmpty(nonEmptyObj)); // false