How to check for an empty/undefined/null string in JavaScript?
Javascript | string | check | how to
- To check for a truthy value:
if (strValue) {
// strValue was non-empty string, true, 42, Infinity, [], ...
}
- To check for a falsy value:
if (!strValue) {
// strValue was empty string, false, 0, null, undefined, ...
}
- Empty string (only!)
To check for exactly an empty string, compare for strict equality against ""
using the ===
operator:
if (strValue === "") {
// strValue was empty string
}
- To check for not an empty string strictly, use the
!==
operator:
if (strValue !== "") {
// strValue was not an empty string
}
- Using type casting:
if (Boolean(str)) {
// Code here
}
Typecast the variable to Boolean, where str
is a variable.
It returns
false
fornull
,undefined
,0
,000
,""
,false
.It returns
true
for all string values other than the empty string (including strings like"0"
and" "
)