Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to check if an object is empty

Short answer

Object.keys() returns an array of keys. An empty object has none:

const filters = {};
 
console.log(Object.keys(filters).length === 0);

Output:

true

null and undefined

Object.keys(null) throws an error. If the value may be missing, check that first:

const isEmpty = (value) => value == null || Object.keys(value).length === 0;
 
console.log(isEmpty({}));
console.log(isEmpty(null));
console.log(isEmpty({ page: 1 }));

Output:

true
true
false

Common mistake

An empty object is truthy, so if (obj) does not detect emptiness. Comparing with {} does not work either:

const filters = {};
 
console.log(filters ? 'has filters' : 'empty');
console.log(filters === {});

Output:

has filters
false

Functions used in this recipe

  • Object.keys — Returns an array of an object's property names.

Thanks for reading!

Donate to the site — we work hard for you.