How to Check if an Object is Empty in JavaScript or Node.js

Coding for the happy path is pretty simple. Handling the rest is a much harder challenge.

A typical example is a check for the existence of some data, like is the client sending valid data or just an empty object? This tutorial shows you how to detect if an object is empty in JavaScript.

Node.js Series Overview

Detect if an Object is Empty in JavaScript or Node.js

JavaScript provides the Object.keys() method returning the array of keys from the given object. You can leverage this method detecting whether the number of keys is zero which tells you a given object is empty:

const user = {}

const isEmpty = Object.keys(user).length === 0  

You may also create yourself a helper function accepting the object as a parameter and returning true when empty and false when not:

function isEmpty(object) {  
  return Object.keys(user).length === 0

// true

isEmpty({ name: 'Marcus' })  
// false


Explore the Library

Find interesting tutorials and solutions for your problems.