How to Check if an Object is Empty in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 8, 2022

banner

Photo from Unsplash

Check if an Object is Empty in JavaScript #

To check if an object is empty in JavaScript:

  1. Pass the object to the Object.keys method to get an array of the object's keys
  2. Access the length property on the array
  3. Check if the length of keys is equal to 0, if it is, then the object is empty
index.js
const obj = {}; const isEmpty = Object.keys(obj).length === 0; console.log(isEmpty); // 👉️ true

We used the Object.keys method to get an array of all of the object's keys.

The Object.keys method returns an empty array if the object has no key-value pairs (if it's empty).

Here's what calling Object.keys on a non-empty object looks like.

index.js
const obj = {a: 1, b: 2}; console.log(Object.keys(obj)); // 👉️ ['a', 'b'] const isEmpty = Object.keys(obj).length === 0; console.log(isEmpty); // 👉️ false

Alternatively, you can use a for...in loop.

To check if an object is empty in JavaScript:

  1. Use a for...in loop to iterate over the properties of the object.
  2. If there is even a single iteration, the object is not empty.
  3. If there aren't any iterations, the object is empty.
index.js
const obj = {}; function isEmpty(object) { for (const property in object) { return false; } return true; } console.log(isEmpty(obj)); // 👉️ true

We created a helper function which attempts to iterate over the properties of an object.

If there is even 1 iteration, we know that the object has at least 1 key-value pair and is not empty.

If there aren't any iterations, then the object is empty.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.