Introduction
By default, JavaScript provides a property called length which could let you know if there are values inside the array, but when it comes to objects JavaScript doesn't provide any feature to determine if an object is empty. However, we could get around this issue easily by adding a tiny amount of code to your application.
In this blog post, we'll be looking at three different ways we can check if the object is empty.
Using the Object.keys method
The keys method returns an array that contains an array of property names of the object under consideration. We could check the length of this array to determine if an object is empty. If the object has no properties in it, i.e. it's empty, the array length will be zero.
- const user = {};
- Object.keys(user).length === 0;
Using for .. in loop
The for .. in statement is used to iterate over the enumerable properties of the object under consideration.
- const user = {};
-
- function isEmpty(obj) {
- for (let key in obj) {
- if (obj.hasOwnProperty(key)) {
- return false;
- }
- }
-
- return true;
- }
-
- isEmpty(user);
The hasOwnProperty method on the object is used to determine if the property under consideration exists directly within the object or is being inherited from the prototype chain.
Using JSON.stringify method
The Stringify method converts the input into a string and returns that string. If we try to stringify an empty object, it'll simply return opening and closing curly brace as a string.
- const user = {};
- JSON.stringify(user) === '{}'