JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to check if an object is empty in JavaScript?

To check if an object is empty in JavaScript, follow the following steps:

  1. First, call the Object.keys() method and pass the object which you want to check.
  2. Object.keys() method returns an array having all the object's keys as array elements. Next, using the if statement, check if the length of the returned array is 0 or not.
  3. If the length of the array is 0, then the object is empty; otherwise, the object is not empty.
let obj = {};

let length = Object.keys(obj).length; //0
if(length === 0){
  console.log('Object is empty.');
}

JavaScript provides the Object.keys() method that returns an array whose elements are the object's keys.

let employee = {
  firstName: "Mohit",
  lastName: "Natani",
  salary: 100000
};

console.log(Object.keys(employee)); //["firstName", "lastName", "salary"]

So, if an object is empty, then the returned array will have no elements.

An alternative approach is to use for...in loop.

The for...in loop iterates over the keys of an object. So, if an object is empty, then the body of the for...in loop will be skipped. The following statement after the loop will be executed.

let obj = {};
let empty = true;

for(let key in obj){
  empty = false;
}
if(empty){
  console.log('Object is empty.');
}else{
  console.log('Object is not empty.');
}

Output

Object is empty.

Note:The methods explained in this tutorial can be used in React and Node.JS to check if an object is empty or not.

Recommended Posts