A Practical Guide to Detecting "Empty" Values in JavaScript

A Practical Guide to Detecting "Empty" Values in JavaScript
Photo by Goran Ivos / Unsplash

In day-to-day JavaScript development, especially when working with forms, APIs, or data validation, there's one recurring need:

"Is this value empty?"

While it sounds simple, "empty" can mean different things depending on context — and JavaScript doesn't give us a built-in one-size-fits-all function for it.

Let’s change that.


✅ The isEmpty() Utility Function

Here’s a reusable function that covers the most common use cases:

const isEmpty = val =>
  val === undefined ||
  val === null ||
  (typeof val === "string" && val.trim() === "") ||
  (Array.isArray(val) && val.length === 0) ||
  (typeof val === "object" && !Array.isArray(val) && Object.keys(val).length === 0);

This function returns true for all of the following:

isEmpty(undefined);       // true
isEmpty(null);            // true
isEmpty("");              // true
isEmpty("   ");           // true (whitespace only)
isEmpty([]);              // true
isEmpty({});              // true

And returns false for these:

isEmpty("Hello");         // false
isEmpty([1, 2, 3]);       // false
isEmpty({ a: 1 });        // false

🔍 Why Not Just !val?

A common beginner mistake is writing something like:

if (!val) { ... }

While this works for null, undefined, 0, false, and "", it fails to detect:

  • Empty arrays: []
  • Empty objects: {}

And worse, it wrongly treats 0 and false as empty, which are valid values in many situations.


📌 Use Cases in the Real World

This utility is useful for:

  • Form validation: Avoid submitting empty strings or objects.
  • API request sanitization: Skip empty fields in the payload.
  • Conditional rendering: Only show data when there's something meaningful.

⚠️ Considerations

  • This function does not handle special types like Map, Set, or Date. If you need those, you can extend it.
  • It treats only own properties on objects. Prototype properties do not count (as expected).
  • It doesn't treat 0 or false as empty — because they're usually intentional values (e.g. a switch toggle or numeric input).

🛠️ Optional Enhancements

If you want to go further, you could add:

(val instanceof Date && isNaN(val.getTime())) // treat invalid dates as empty

Or check for Set and Map:

(val instanceof Set || val instanceof Map) && val.size === 0

But for 90% of use cases, the base isEmpty() is lightweight and highly effective.


🚀 Finally

In JavaScript, "empty" is a nuanced concept. Building a utility like isEmpty() gives your code clarity, predictability, and avoids hidden bugs caused by loose truthiness checks.

Whether you're validating user input, cleaning data before sending it to an API, or writing generic utilities — having a solid definition of “empty” will make your codebase cleaner and safer.

Support Us