How to Check if an Object is Empty in JavaScript

Published on Sunday, 30 March 2021

In this article, I will be sharing 6 different JavaScript methods you can use to check if an object is empty or not.

Let's start with creating an empty object using literal syntax...

1const myObject = {}
2

1. Object.entries()

This method returns an array containing the [key, value] pairs found in the object passed in as an argument. To check if an object is empty, check if the length of the array is 0.

1Object.entries(myObject).length === 0;
2// 0
3
4return Object.entries(myObject).length === 0 ? true: false
5// true
6

2. Object.keys()

This method returns an array of strings that contains enumerable properties of the object passed as an argument. It returns an array of [ keys ]

1Object.keys(myObject).length === 0;
2// 0
3
4return Object.keys(myObject).length === 0 ? true: false
5// true
6

You can also create an isEmpty function and pass in the object as a parameter

1function isEmpty (myObject) {
2
3return Object.keys(myObject).length === 0 ? true: false
4
5}
6
7isEmpty(myObject); // true
8

3. Object.getOwnPropertyNames()

It returns an array of strings that corresponds to the properties found in the object passed as an argument. This method calls GetOwnPropertyKeys under the hood.

1 Object.getOwnPropertyNames(myObject).length === 0;
2// 0
3
4if(Object.getOwnPropertyNames(myObject).length === 0) { // return something};
5

4. !myObject.key

It checks if the [key] is present in myObject. Use this when you know the properties that the object is supposed to have.

1let result = '';
2
3my.object.id // undefined
4
5if (!myObject.id) result = 'object is empty'
6
7console.log(result) // object is empty
8

Note: this won't work myObject[id], JavaScript will throw an error.

Using a JavaScript Library

5. UnderScore.js

_.isEmpty(collection) Returns true if collection has no elements. For strings and array-like objects _.isEmpty checks if the length property is 0.

1_.isEmpty([1, 2, 3]);
2
3=> false
4
5_.isEmpty({});
6
7=> true
8

6. Lodash.Js

_.isEmpty() Method Checks if the value is an empty object, collection, map, or set. Objects are considered empty if they have no own enumerable string keyed properties.

1_.isEmpty({ 'a': 1 });
2// => false
3
4_.isEmpty(myObject)
5// true
6

Discuss on Medium

Recommended Reads

Articles written by Kelechi Ogbonna. All rights reserved

Built with NextJs Typescript and TailwindCSS