How do I test for an empty JavaScript object?
If you want a quick "fast food" solution to check if an object is empty, use Object.keys() along with a length check:
Just call isEmpty(yourObj)
. If the object has no properties of its own and is a basic Object
, it will return true
.
More than meets the eye
Sometimes, textbooks don't cover real-world hiccups. An object may seem straightforward, but it's Objectception all the way down. When dealing with objects, we have to be sure they genuinely have no own enumerable properties. Object.keys()
is suitable for ES5+ environments. We also do a constructor check to guard against JavaScript's practical jokes where null
, arrays, and cross-realm objects are also types of objects.
Cross-realm and unusual prototypes
Some objects have seen more of the multiverse than Doctor Strange. Cross-realm objects and ones with unique prototypes need special care:
Legacy environments, where people still remember dial-up tones, can use Object.prototype.hasOwnProperty.call(obj, key)
instead of Object.hasOwn(obj, key)
.
What's in the box — Edge case handling
Prototype-free Objects
Living off the grid, ah? In JavaScript, you can create objects with no prototype using Object.create(null)
. Our 'hardened' isEmptyObject
function pitched a tent here as well.
Symbolic times
Object.keys()
doesn't get Symbol
properties. They are like hipsters at a metal concert in ES6 and above. We can include them as such:
Libraries in action
If you like your project frameworks thick, like a double cheeseburger, don't reinvent the wheel. Use _.isEmpty(obj)
from lodash or $.isEmptyObject(obj)
from jQuery. Just remember to wear a bib for the sauce.
In-depth detection
Not everything is plain JavaScript
Avoid JSON.stringify(obj) === "{}"
. It's slower than a snail climbing Mount Everest. It doesn't see non-enumerable properties either.
Keep performance in mind
Jared Leto won an Oscar for playing a method actor. Be like Jared. Test your methods in their actual parts. Use tools like JSBench.me for performance comparisons.
Don't play with fire: Type safety
Distinguishing between wave and particle is important in quantum physics. Similarly, JavaScript objects and other types require different treatments. Your isEmpty
function needs to differentiate them else face the black hole of unexpected bugs.
Was this article helpful?