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.

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay