How to Check if Object is Empty in JavaScript

In this tutorial, I will explain to you how you can check if the object is empty in JavaScript.

JavaScript Object

Object is anything that exists in the real world. It’s a real-world entity.

As a car, it’s a real-world object. A car has properties like weight, color etc.

Objects are variables too but it consists of various values. We can define an object in JavaScript with the const keyword it’s a common way to define the object in JavaScript.

To check if Object is Empty or not:-

In JavaScript we have various methods to check the object if it is empty or not. Here I’ll discuss with you the simplest method for checking if the object is empty object or not.

First of lets understand how we define or declare object in JavaScript.

In JavaScript we declare object as name:value pairs, called keys.

Like,

const obj={  Name: 'Sachin'
              Score:78};  //object declaration in JavaScript

Object.keys(object)  method

Now, to check if our declared object is empty or not we can use JavaScript built-in function Object.keys(object)  using this method we can check the keys in the object, but for checking the number of keys we can use length property with this method, while using length property we get 0 as the output it means that our object is empty have no keys.

//to check if the JavaSCript object is empty 
const obj={ Name:'Sachin', Score:89 }; 
//now to check it if it is empty or not 
console.log(Object.keys(obj).length===0);  //it will return false as the output, 
//since our obj(object) is not empty it have keys in it.

//Now lets  declare another object  


const obj1={};   //it is an empty object have nothing

//now to check  this object using above same function


console.log(Object.keys(obj1).length===0);  //it will return true ,

//since our object  obj1 is an empty object

Output

If we run the code, then we will see the output given below:

false
true

Leave a Reply

Your email address will not be published.