How to find if a JavaScript object is empty

If you want to test if a JavaScript object is empty, you can use this simple one-liner. Just replace foobar with your object:


You can also turn this into a reusable function:

function objectIsEmpty(obj) {
return !Object.keys(obj).length

Then, to test if an object was empty, you could do something like:

if (objectIsEmpty(obj)) {
// The object is empty.
} else {
// The object isn't empty.

How it works

Object.keys returns an array of the object’s keys. For instance, { a: 1, b: 2 } would return ["a", "b"]. We measure the length of this string to return either a 0 (which is a falsy value in JavaScript) or a number that’s not zero (which is a truthy value). Then, the ! operation is performed which converts a falsy or truthy value into its opposite boolean.

And there you have it: a simple, one-line way to detect if an object is empty.