How to Check if An Object is Empty in JavaScript

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.

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.

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 ]

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

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.

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.

Note: this won’t work “ myObject[id] ”, JavaScript will throw a syntax 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.

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.

--

--

Software Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store