Empty Object

Today I learned this code doesn't work as I think it would.

objectName !== {} ? displayObject : null

The correct ways to check for empty objects are:

  • use Object.keys
    Object.keys(obj).length === 0
    Note: We can also check this using Object.values and Object.entries.
  • use JSON.stringify
    JSON.stringify(obj) === '{}'
  • Looping over object properties with for…in
function isEmpty(obj) {
for(let prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
}

Source -> More ways to check