user
How to check for an empty JS string ?
alphonsio

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:

1. Using the .length Property

The 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

2. Using !str for Truthy/Falsy Values

In 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)

3. Handle null or undefined Explicitly

If 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

4. Combining Length Check with 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

Best Approach?

  • Use .length if you're strictly checking for an empty string ("").
  • Use trim().length if you also want to consider strings with only whitespace as empty.
  • Add checks for null or undefined explicitly, if your data might contain those values.