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 = {}
Table of Contents
1. Using for…in loop
function isObjEmpty(obj) { for(key in obj) return false; return true; } isObjEmpty({}) //true isObjEmpty({a:1}) // false
2. Using Object.keys()
function isObjEmpty(obj) { return Object.keys(obj).length === 0 && obj.constructor === Object } isObjEmpty({}) //true isObjEmpty({a:1}) // false
3. Using JSON.stringify()
function isObjEmpty(obj) { return JSON.stringify(obj) === "{}" } isObjEmpty({}) //true isObjEmpty({a:1}) // false
4. Using Object.entries()
function isObjEmpty(obj) { return Object.entries(obj).length === 0 && obj.constructor === Object } isObjEmpty({}) //true isObjEmpty({a:1}) // false