In JavaScript, a string can be empty, null, or undefined, and each state means something different. When developers ask whether a JavaScript string is null or empty, they usually need a reliable way to validate user input, API responses, configuration values, or optional function arguments. The challenge is that JavaScript treats these values differently: an empty string is still a string, null is an intentional absence of value, and undefined usually means a value was never assigned. A good validation check must account for those differences without accidentally rejecting valid values such as "0", "false", or a string containing only spaces Which is the point..
Understanding Null, Undefined, and Empty Strings
Before writing a check, it helps to separate the three common states.
- Empty string:
""is a primitive string with a length of0. It is a valid string value, but it contains no characters. - Null:
nullis a special value that represents the intentional absence of an object or value. It is not a string. In fact,typeof nullreturns"object", which is a long-standing JavaScript quirk. - Undefined:
undefinedmeans a variable has been declared but not assigned, a property does not exist, or a function argument was omitted. It is also not a string. - Whitespace-only string:
" "or"\t\n"is not empty by length, but it is often treated as empty in form validation because it contains no visible characters.
These distinctions matter because a check that works for "" may throw an error for null, and a check that catches null may also reject valid non-string values Most people skip this — try not to. Nothing fancy..
The Most Reliable Check for Null or Empty
If you only need to detect null, undefined, and the empty string, use an explicit comparison:
function isNullOrEmpty(value) {
return value === null || value === undefined || value === "";
}
This function is clear and predictable. It returns true for null, undefined, and "". It returns false for "hello", "0", "false", and " ".
A shorter version uses the loose equality operator with null:
function isNullOrEmpty(value) {
return value == null || value === "";
}
The expression value == null is a well-known JavaScript idiom that matches both null and undefined while not matching 0, false, or "". Now, the second part, value === "", handles the empty string. This version is concise, but some teams prefer explicit === null || === undefined for readability Simple, but easy to overlook..
Why if (!str) Is Not Always Enough
Many developers use a falsy check:
if (!str) {
// runs for "", null, undefined, 0, false, and NaN
}
For a variable that is guaranteed to be a string, null, or undefined, this works for detecting empty or missing values. Even so, it is