DEV Community

Cover image for How to Check if an Object is Empty in JavaScript (benchmark)
YURII DE.
YURII DE.

Posted on

How to Check if an Object is Empty in JavaScript (benchmark)

Using Object.keys()

169,635 ±1.83% 2% slower

function isEmptyObject(obj) {
  return Object.keys(obj).length === 0;
}
Enter fullscreen mode Exit fullscreen mode

Using for...in loop (WON)

172,973 ±0.97% fastest

function isEmptyObject(obj) {
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      return false;
    }
  }
  return true;
}
Enter fullscreen mode Exit fullscreen mode

Using JSON.stringify

164,737 ±0.83% 5% slower

function isEmptyObject(obj) {
  return JSON.stringify(obj) === '{}';
}
Enter fullscreen mode Exit fullscreen mode

Using Object.entries()

169,838 ±1.34% 2% slower

function isEmptyObject(obj) {
  return Object.entries(obj).length === 0;
}
Enter fullscreen mode Exit fullscreen mode

Test of benchmark: https://jsperf.app/govaru

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay