Check object is empty or not in JavaScript

In our code object can empty or not. So we need to check object is empty or not. There are several way to check object in valid or not. Let see various approach to solve this issue.

let empty_obj = {}

1. Using for…in loop

function isObjEmpty(obj) {
    for(key in obj) return false;
    return true;
}

isObjEmpty({}) //true
isObjEmpty({a:1}) // false
 check object is empty or not
for..in

2. Using Object.keys()

function isObjEmpty(obj) {
   return Object.keys(obj).length === 0 && obj.constructor === Object
}

isObjEmpty({}) //true
isObjEmpty({a:1}) // false
 check object is empty or not
Object.keys()

3. Using JSON.stringify()

function isObjEmpty(obj) {
   return JSON.stringify(obj) === "{}"
}

isObjEmpty({}) //true
isObjEmpty({a:1}) // false
 check object is empty or not
JSON.stringify()

4. Using Object.entries()

function isObjEmpty(obj) {
   return Object.entries(obj).length === 0 && obj.constructor === Object
}

isObjEmpty({}) //true
isObjEmpty({a:1}) // false
 check object is empty or not
Object.entries()

Leave a Reply