The best way to check if a JavaScript string is empty (whether there's any value) is to use the following:
if (myString) {
// Do something
}
The following alternative will return true only if the type of myString
is a string and the string is empty.
if (myString === '') {
// Do something
}
You may also want to check if a string is empty or contains only spaces.
To check if a JavaScript string is empty (i.e., has a length of 0), you can use a simple conditional statement. Here's how to do it:
.length
PropertyThe most straightforward way to check if a string is empty is by checking its length
:
function isEmpty(str) {
return str.length === 0;
}
// Examples
console.log(isEmpty("")); // true
console.log(isEmpty(" ")); // false (contains a space)
console.log(isEmpty("Hi")); // false
!str
for Truthy/Falsy ValuesIn JavaScript, an empty string (""
) is a falsy value. You can use this to check for an empty string, but note that this approach will also treat null
, undefined
, or 0
as "empty."
function isEmpty(str) {
return !str;
}
// Examples
console.log(isEmpty("")); // true
console.log(isEmpty(" ")); // false (contains a space)
console.log(isEmpty("Hello")); // false
console.log(isEmpty(null)); // true (null is treated as falsy)
console.log(isEmpty(undefined)); // true (undefined is treated as falsy)
null
or undefined
ExplicitlyIf you want to strictly check for an empty string without mistakenly treating null
or undefined
as empty, you can use:
function isEmpty(str) {
return str !== null && str !== undefined && str === "";
}
// Examples
console.log(isEmpty("")); // true
console.log(isEmpty(" ")); // false
console.log(isEmpty("Hi")); // false
console.log(isEmpty(null)); // false
console.log(isEmpty(undefined)); // false
trim()
If you want to check if a string is empty or contains only whitespace (e.g., " "
), you can combine .trim()
with a length check:
function isEmptyOrWhitespace(str) {
return str.trim().length === 0;
}
// Examples
console.log(isEmptyOrWhitespace("")); // true
console.log(isEmptyOrWhitespace(" ")); // true
console.log(isEmptyOrWhitespace("Hi")); // false
console.log(isEmptyOrWhitespace(" Hi ")); // false
.length
if you're strictly checking for an empty string (""
).trim().length
if you also want to consider strings with only whitespace as empty.null
or undefined
explicitly, if your data might contain those values.