DEV Community

Paramanantham Harrison
Paramanantham Harrison

Posted on • Originally published at jsmates.com on

Check whether object is empty in JavaScript

JS objects have a method to get all the keys in the object.

const author = {
  firstName: 'Param',
  lastName: 'Harrison'
};

console.log(Object.keys(author)); // Output - ["firstName", "lastName"]
Enter fullscreen mode Exit fullscreen mode

To check whether the object is empty or not, you can check the number of keys.

if (Object.keys(author).length === 0) {
  console.log('Author object is empty');
} else {
  console.log('Author object is not empty');
}
Enter fullscreen mode Exit fullscreen mode

Since we have the keys, it will show Author object is not empty in the console output.

Now, remove the keys in the object and check,

const author = {};

console.log(Object.keys(author)); // Output - []
Enter fullscreen mode Exit fullscreen mode

It will display Author object is empty in the console.

JS Mates launched our REST API Design using Node Js course for free, check it out here. It is an interactive text course.
Follow us for more free courses on JavaScript ecosystem on Twitter. Subscribe to our weekly newsletter for more goodies here.

Top comments (0)