DEV Community

Cover image for Empty Object?
Manav Misra
Manav Misra

Posted on

Empty Object?

At times, for example, when receiving an object as a function parameter, we wish to know if we have received an empty object or not.

This can especially be the case if some JSON data in a request body is not parsed correctly; our server then ends up with an empty object.

function check4ValidObjectWithKeys(someObj) {
  if (Object.entries(someObj).length) {
    return "👍🏾"

  return "👎🏾"
Enter fullscreen mode Exit fullscreen mode


...along with things like Object.keys and Object.values (all would work for the example) creates an array of either...

  1. The entries - 🔑/value pairs (it's an array of arrays!)
  2. Just the 🔑s - again, an array
  3. Just the values - what is it? array!

.length... us the length (number of items) in an array as a number.

Coercion with if

if (Object.entries(someObj).length) { translates to:

  1. Get the entries from the object as an array
  2. If the length of that array is considered as 'truthy' (non-zero)...

Top comments (0)