How to check if an Object is Empty in JavaScript

Javascript check object is empty example; In this post you will learn how to check if an Object is Empty in JavaScript;

Example 1:

To check if an object is empty in JavaScript we need to pass the object to the Object.keys method to get an array of the object’s keys then we access the length property on the array. Next we check if the length of keys is equal to 0, if it is, then the object is empty.

const obj = {};

const isEmpty = Object.keys(obj).length === 0;
console.log(isEmpty); // true

Example 2:

Here’s what calling Object.keys on a non-empty object looks like.

const obj = {first: 1, second: 2};

console.log(Object.keys(obj)); // ['first', 'second']

const isEmpty = Object.keys(obj).length === 0;
console.log(isEmpty); // false

Example 3:

The for…in statement will loop through the enumerable property of the object.

const obj = {};

function isEmpty(object) {
  for (const property in object) {
    return false;
  }
  return true;
}

console.log(isEmpty(obj)); // true