How to check if an object is empty in JavaScript

Learn how to see if a variable is equivalent to an empty object

Suppose you want to check whether the value you have is equal to the empty object, you can create the value using object literal syntax:

const emptyObject = {}

How can you do this?

useObject.entries()Features.

It returns an array containing the enumerable properties of the object.

Its usage is like this:

Object.entries(objectToCheck)

If an empty array is returned, it means that the object does not have any enumerable properties, which in turn means that the object is empty.

Object.entries(objectToCheck).length === 0

You should also ensure that the object is actually an object by checking whether its constructor is an object.Objectpurpose:

objectToCheck.constructor === Object

Lodash, a popular library, providesisEmpty()Features:

_.isEmpty(objectToCheck)

Download mine for freeJavaScript beginner's manual


More js tutorials: