How to Check if JavaScript Object is Empty

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 is the Object.keys(object). The required object should be passed to the Object.keys(object) then it will return the keys in the object. The length property is used to check the number of keys. If it returns 0 keys, then the object is empty.

//javascript empty object
let obj = {};
function isEmpty(object) {
  return Object.keys(object).length === 0;
}
let emptyObj = isEmpty(obj);
console.log(emptyObj);

The hasOwnProperty() Method

The second method is looping through the object using object.hasOwnProperty(key). When the object contains the "key" property using the object.hasOwnProperty() method, a function is created. This would return true if it could find no keys in the loop, which means that the object is empty. If any key is found, the loop breaks returning false. Use this method for older browsers that do not support the first method.

let obj = {name: 'W3Docs'};
function isEmptyObj(obj) {
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      return false;
    }
  }
}
let emptyObj = isEmptyObj(obj);
console.log(emptyObj);

The JSON.stringify Method

If you JSON.stringify the object and the result is an opening and closing bracket, it means that the object is empty.

let obj = {};
function isEmptyObj(object) {
  return JSON.stringify(object) === '{}';
}
let emptyObj = isEmptyObj(obj);
console.log(emptyObj);

Object.keys()

Object.keys() returns the array whose elements are strings that correspond to the enumerable properties found directly upon the object. The property order is similar to that given by the object manually in a loop applied to the properties.

Object.keys() is used to return enumerable properties of a simple array, of an array like an object, and an array like object with random ordering.

The JSON (JavaScript Object Notation) is a notable format that represents objects and values. This format was created for JavaScript, but it is also used by server-side languages.

JavaScript provides two methods of converting: JSON.stringify and JSON.parse. The first is used for turning objects into JSON and the second one for converting JSON back into an object.


Do you find this helpful?

Related articles