How to Check if an Object is Empty in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 05 20211 min read

banner

Photo by MusicFox Fx

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 all the keys of the object
  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
// Supported in IE 9-11 const obj = {}; const isEmpty = Object.keys(obj).length === 0; console.log(isEmpty); // ๐Ÿ‘‰๏ธ true

In the code example, we used the Object.keys method to get an array of all of the keys of the object.

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

An alternative approach is to try to iterate over the properties of the object. If there is even a single iteration, then the object is not empty.

index.js
// Supported in IE 6-11 const obj = {}; function isEmpty(object) { for (const property in object) { return false; } return true; } console.log(isEmpty(obj)); // ๐Ÿ‘‰๏ธ true

In the code snippet, we have 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 an empty object.

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

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee