How to Check if JavaScript Object is Empty
Read this tutorial and find methods of checking whether a JavaScript object is empty or not. Choose the best one for you and get the code immediately.
There are several methods for checking if the JavaScript object is empty. Let’s discuss and explain each of them separately.
The Object.keys Method
The first method uses <kbd class="highlighted">Object.keys()</kbd>. Pass the object to this method, which returns an array of its enumerable property names. Use the length property to check the number of keys. If the length is 0, the object is empty.
Javascript empty object
The hasOwnProperty() Method
The second method iterates through the object using a <kbd class="highlighted">for...in</kbd> loop and checks each property with <kbd class="highlighted">object.hasOwnProperty(key)</kbd>. If the method finds a key, the function returns false. If the loop completes without finding any keys, it returns true, indicating the object is empty. This approach is useful for environments that do not support Object.keys().
Javascript empty object
The JSON.stringify Method
If you JSON.stringify the object and the result is "{}", it means that the object is empty.
Javascript empty object