Register Login

Check if Object is Empty in JavaScript

Users can term everything as an Object in JavaScript. They can use a filled or an empty object while creating an object. But to know whether a JS object is empty, users should know different methods to check an empty object in JavaScript.

This article will discuss the different ways to test for an empty object in JavaScript.

What is an object in JavaScript?

In JavaScript, an object is a collection of different data and has its types and properties. Users can define everything in JavaScript as objects. Usually, objects consist of several functions and variables known as the methods and properties of that object when they are inside it.

While going through objects, users should know what empty JS objects are and how to check an empty object. Those objects which hold no properties or types are known as empty objects.

Different ways to test for an empty object in JavaScript are as follows:

Method 1: Using the Object.keys(object) method:

Users can use the Object.keys(object) method and the typeof operator to check whether they are dealing with an empty JavaScript object or not. It has no enumerable properties.

Also, since null == undefined is true, a != null will detect both null and undefined values. In the code example given below, the isEmptyObject() function will test if an object is empty. However, it will only check those objects that users created using "{}" or "new Object()."

Also, users can use the length property to the result to find the number of keys. The length property will return zero if the JS object is empty as it does not contain any key.

Code Snippet:

function demo(a) {
    if(typeof a === 'object' && a != null && Object.keys(a).length !== 0){
        return false;
    } else {
        return true;
    }
}

// Here, we will test a few values    
console.log(demo({})); // This will print: true
console.log(demo({name: "JavaScript", age: 19})); // This will print: false
console.log(demo(null)); // This will print: true
console.log(demo(undefined));

Output:

Run Code

Explanation:

The Object.keys(object) will return true if the object is empty, and if it contains properties or values, it will return false. Users can also test a JS object using Object.values and Object.entries. It is generally the simplest technique to resolve if a JS object is empty.

Method 2: Using the Object.getOwnPropertyNames() method:

When users use the Object.getOwnPropertyNames() method in JavaScript, it returns an array of every property of the given object. Though users might find this work similar to the JavaScript Object.keys() method, there is a difference.

While using the Object.getOwnPropertyNames() method, it also accepts  the non-enumerable properties, but the Object.keys() only accepts enumerable properties. Many users consider these two the same, but this simple difference can take make a huge sense in JavaScript code.

Code Snippet:

function demo(a) {
    return Object.getOwnPropertyNames(a).length === 0;
}
console.log(demo({})); // It gives the output as true
var x = {"Hello": "1"};
console.log(Object.getOwnPropertyNames(x).length); // It gives the output as 1
console.log(demo(x));

Output:

Run Code

Explanation:

As we can see in the above code example, while testing an empty object in JavaScript, Object.getOwnPropertyNames() operates similarly to using Object.keys().

Method 3: Use the looping method to loop through the JS object using the object.hasOwnProperty(key):

Let us see another method of JavaScript to check if an object contains properties or if the JS object is empty. In this method, users create a function where the JS object is looped over and tested if it has the 'key' property operating the object.hasOwnProperty() method.

If the function finds no keys in the loop, it will return true, which indicates that the JS object is empty. If it encounters any key, the loop breaks and returns false. This method will also work for the older versions of the browsers. The first two methods may not support it.

Code Snippet:

<h1 style = "color: red">JavaScript </h1>
 <b>How to test if an object is empty in JavaScript?</b>
 
 <p>Click the button to test  if the object is empty</p>
 <p>Output for empty object:<span class="Empty"></span></p>
 <p>Output for non-empty object: <span class="NonEmpty"></span></p>

 <button onclick="check_the_Object()">Click here</button>
 
<script type="text/javascript">
	function check_the_Object(){
		let emptyObj = {}
   	 	let nonEmptyObj = {
			title: 'Title 1',
			info: 'Sample Info'
		}

   		ans1 = demo(emptyObj);
   		document.querySelector('.Empty').textContent = ans1;

   		ans2 = demo(nonEmptyObj);
		document.querySelector('.NonEmpty').textContent = ans2;
  	}

 	function demo(object) {
	   for (var key in object) {
		   if (object.hasOwnProperty(key)) {
		 		return false;
			}
   		}
		return true;
  	}
</script>

Output:

Run Code

Explanation:

In this example, we have used HTML with JavaScript to check an empty object. The looping method returns true when we pass an empty object while false when we pass an object with a property.

Method 4: Using the JSON.stringify:

Users can use this JSON.stringify method to convert a JavaScript object into a JSON string. So they can reach the result with "{}" and check if the given JS object is empty.

Code Snippet:

function demo(a){
    return JSON.stringify(a) === '{}';
}

console.log(demo({})); // It returns the output as true
var i = {"Hello":"1"};
console.log(JSON.stringify(i)); // It returns the output as {"Hello":"1"}
console.log(demo(i));

Output:

Run Code

Conclusion:

We hope this article has catered to the different methods to test whether users are dealing with an empty JavaScript object or not. You can say that all the methods are better than the others, but according to the condition of the program, users need to use these methods.

Lastly, we have shown the code examples and outputs according to the following methods, with one example using both HTML and JavaScript.


×