How to safely check if an object is really empty?

const object1 = {hallo: 'world'}
const object2 = {}

// returns: false
Object.entries(object1).length === 0 && object1.constructor === Object

// returns: true
Object.entries(object2).length === 0 && object2.constructor === Object
Copy

November 26th, 2019

# Object.entries() - Check if an object is empty

Add to bookmarks

Object.entries() returns an array of the object's properties. Then it's possible to check the length of this array. An empty array has no properties. The second condition is what makes this snippet safe, because we also check if the variable was an object.

HomeBookmarks