How do I check for an empty/undefined/null string in JavaScript?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
There is no single "empty string" check in JavaScript, because "", null, and undefined are different values. The right test depends on whether you want a quick falsy check, a strict string-only check, or a whitespace-aware check.
The Quick Falsy Check
If your variable should either be a non-empty string or "missing", the shortest test is:
This is concise, but it is broad. It treats several non-string falsy values as empty too.
That means it is safe only when you already know str is either:
- a string
- '
null' - '
undefined'
If 0 or false can appear, !str may be too aggressive.
Strict Check for Empty, null, or undefined
If you want to check only those three cases, be explicit:
This avoids accidentally treating 0 or false as empty.
You can wrap that in a helper:
Check for Whitespace-Only Strings
Sometimes " " should count as empty too. In that case, trim first:
The value == null check is a deliberate shorthand that matches both null and undefined only.
Why typeof Matters
Calling .trim() on a non-string throws an error:
That is why a safe helper usually guards with typeof value === "string" before trimming.
Different Use Cases Need Different Helpers
Here are three practical utilities:
And a combined version:
Choosing the right one makes your intent obvious to the next reader.
Use in Form Validation
This pattern is common in forms:
That accepts real text while rejecting missing and whitespace-only input.
Avoid Overusing Loose Equality
You may see this:
That is usually less clear than a deliberate helper or explicit comparison. Loose equality can coerce values in surprising ways, so use it only when you actually want that behavior. The common exception is value == null, which is often intentionally used to mean "null or undefined".
Common Pitfalls
The biggest mistake is using !str when the variable might contain non-string falsy values such as 0 or false. That can turn a general falsy check into a buggy empty-string check.
Another issue is calling .trim() without verifying the type first. If the variable is not a string, the code throws rather than returning a clean boolean result.
Finally, be explicit about whether whitespace-only strings should count as empty. Different applications make different choices, and bugs often come from silently assuming the wrong rule.
Summary
- Use
!stronly when broad falsy behavior is acceptable. - Use strict equality when you mean exactly
"",null, orundefined. - Use
.trim()only when you want whitespace-only strings to count as empty. - Guard
trim()with a type check so non-string values do not throw. - Write a small helper with a clear name so the intended rule is obvious.

