How to check empty objects in JavaScript

A collection of properties is stored in an object. In an object, there is an association of a name, also called a key and a value combined with called key and value pairs.

But then, external dependency is not required by it when it refers to small applications. With pure javascript, it is the best method for checking if the Object is empty. Whether it is empty or not is a basic and frequent operation for checking an object. However, there are several methods for determining whether it's empty or not.

Type 1:

With the help of the Object.keys(Object) method in javascript:

The keys in the Object will be returned by the Object.keys(Object) method, which will be passed by the required Object. To check the number of keys, the length property is used for the result. The Object will be empty when the length property returns 0 keys.

Syntax:

Example:

Output:

1) It is the output of before clicking button:

How to check empty objects in JavaScript

2) This is the output for after clicking button:

How to check empty objects in JavaScript

Type 2:

Object loop using Object.hasOwnProperty(key):

When the Object is looped over, then the function is created, and using the Object.hasOwnProperty() method, it checks whether it contains the 'key' property in it. If no keys in the loop are found, then this function would return true, which means that the Object is empty. If any key is encountered, the loop breaks, and the false is returned.

Syntax:

Example:

Output:

1) It is the output of before clicking button:

How to check empty objects in JavaScript

2) This is the output for after clicking button:

How to check empty objects in JavaScript




Latest Courses