- Instant help with your JavaScript coding problems

Check if a string is empty in JavaScript

Question:
How to check if a string is empty in JavaScript?
Answer:
let str = '  ';
if ((str ?? '').trim().length === 0) {
  console.log("The string is empty");
}
Description:

In JavaScript to check if a variable is an empty string is a bit tricky. You need to take into account special cases like what if the value is null or undefined or the string contains whitespace characters. So a generic solution you can use a helper function like this:

function isEmpty(str) {
    if (typeof (str ?? '') === 'string' && (str ?? '').trim().length === 0) {
        return true;
    }

    return false;
}

This code handles boolean and numeric values as not empty.

Share "How to check if a string is empty in JavaScript?"