How to Check if Object is Empty in JavaScript


In this article we will check how to check if Object is empty in JavaScript.

Checking empty Object is not as easy as finding empty Array in JavaScript. In Array we all need to find the length of the array using array.length , if its empty it will return 0.

However, with Object we have different methods in JavaScript to check for empty Object. Lets checkout each of them with examples.

Method 1 : Using Object.hasOwnproperty()

The hasOwnProperty() method in JavaScript returns a boolean which indicates if the specific property is present in the Object.

Syntax:

hasOwnProperty(prop)

Lets see with an example.

const objectStudent = {
  number : 42
};

console.log(objectStudent.hasOwnProperty('number'));
// expected output: true

console.log(objectStudent.hasOwnProperty('name'));
// expected output: false

Here, we have a Object, objectStudent with a property number. And using hasOwnPropery() method we got the true when we checked for number in it and false for name.

Method 2 : Using Object.keys()

The Object.keys() method in JavaScript returns an array of an given object's own enumerable property names as strings.

Syntax:

Object.keys(obj)

obj : The object with it's enumerable property name that will be returned.

Now, if the return array's length is 0, then we can say that the Object is empty. Let's check it with an example.

const object1 = {
 //empty object
};
console.log(Object.keys(object1).length);
// expected output: 0

Now since we got 0 as a returned value, we know that the given object was empty.

You can also check empty Object using Object.valuesΒ andΒ Object.entries.

Method 3: Using JSON.stringify

You also check if a object is empty using JSON.stringify. All you need to do is stringify the object and if the return data is an empty bracket, then we can say the object is empty.

Lets see an example.

const object1 = {
 //empty object
};
console.log(JSON.stringify(object1))
// expected output: {}

We can write the above code more clearly so it returns a boolean for us to check.

const object1 = {
 //empty object
};
console.log(JSON.stringify(object1) == '{}')
// expected output: true

IMPORTANT : Make sure you write the empty bracket { } inside a string like this '{ }'. If not, the returned value will be false.

Method 4 : Using Lodash and Underscore

Lodash and Underscore is an external library, and we can use it to check for empty object. And it have supports for older browsers too.

Both have to same syntax _.isEmpty()

Example:

_.isEmpty({});

Method 5 : Using jQuery

JQuery is also a JavaScript library which provide us with some handy methods with which we can check for empty object easily.

Example:

jQuery.isEmptyObject({});

Related Topics:

Check if an array includes a value/element in javascript.

How to remove a property from an object in JavaScript?


πŸ’Ύ Recommended Articles