Menu

What is the best way to check for an empty string in JavaScript

3,458 devs read this
What is the best way to check for an empty string in JavaScript

Want to check if a string is empty in JavaScript? There are several ways to do it, but not all are equally readable, safe, or performant. In this article, I’ll break down the best methods—what works, what doesn't, and what I personally use every time.

I originally explored this question after a student asked me about it, and it led me to run performance tests across several popular methods like str === "", str.length === 0, and even if (!str). The results were surprising—and useful.

Quick answer: Use str === "" to check for empty strings in JavaScript. For broader checks (null, undefined, ""), use if (!str).

Using str == ''

The == operator in JavaScript checks for equality after performing type coercion.

This means it attempts to convert the values to the same type before comparing them. For example, 0 == "" and false == "" both return true, even though the types differ.

When using str == "", it will return true only if str is an empty string, but depending on context, it may behave unpredictably if the value being checked isn’t guaranteed to be a string.

Because of this, == is considered less safe for strict comparisons, especially in codebases that value explicitness and reliability.

var str = 'hi';

if (str == '')
{
}

Using str === ''

While == checks for loose equality and allows type coercion, === checks for strict equality—meaning both the value and the type must match. So str === "" is true only if str is explicitly an empty string.

It won’t return true for null, undefined, false, or 0. This makes === the safest and most precise way to check for an empty string when you want to avoid accidental matches from other falsy values.

var str = 'hi';

if (str === '')
{

}

Checking the length of the string

You can also check the length of a string in order to see if it is empty. If the length is zero, then we know that the string is empty of content. This only works however if the value is indeed of a string type and not null or undefined.

If the value is null or undefined, this check would throw an error.

var str = '';

if (str.length == 0)
{

}

In either of these two examples, you will still need to make sure that there are no trailing empty spaces in your string. So you will need to trim them beforehand.

var str = ' ';

if (str.trim().length == 0)
{

}

Using (!str)

In JavaScript, we can run into values like undefined, null, "", or even NaN—all of which are considered falsy. Instead of checking each one individually, JavaScript gives us a more concise way to handle them: the !str pattern.

The following will return true for any falsy value, including null, undefined, "", 0, false, or NaN:

var str = '';

if (!str) {
  // will run if str is any falsy value
}

This is convenient, but there are a few caveats to keep in mind:

  • Performance: In Firefox, this method showed slightly worse performance compared to more specific checks—likely due to the engine evaluating more edge cases. In Chrome, however, the difference was negligible.

  • Clarity: Sometimes, we actually need to know whether a value is specifically null or undefined. For example, an undefined might indicate a logic error or uninitialized variable—something you may want to catch explicitly. With !str, those distinctions are lost in the blanket check.

So while !str is concise and works well in many cases, it’s not always the best choice when precision matters.

Checking null and undefined Values

Things get trickier when null or undefined values come into play. In JavaScript, a null value is not equal to an empty string—so a check like str == "" will return false when str is null.

Also, if you try to access .length on a null or undefined value, JavaScript will throw a runtime error, since those types don’t have properties.

To safely check if a value is both not null/undefined and also an empty string, you’ll need to write a more defensive condition:

if (str != null && str != undefined && str != '') {
  // str is not null, not undefined, and not an empty string
}

While this check is more explicit and avoids exceptions, it also comes with a cost: in my performance tests (below), this version consistently ran the slowest. That makes sense—you're stacking multiple comparisons in a single condition, each of which has to be evaluated individually.

Performance tests

I wanted to find out which method is best however based on various markers, such as performance and usability. To do so I created various scripts to really push these functions to their limit and to track the total execution time.

And here are the very interesting results.

The first thing I wanted to check was the performance difference between the methods listed above. In order to do that, I had to perform each operation a large enough amount of time to the point where I could get a decent enough value that I could use to calculate average execution times.

To give an example, running a loop with 1 million checks, takes roughly 1 - 2 ms. That is not a big enough number where I could make any valid predictions or assumptions. But around 10,000,000 seems to do the job. Here is a quick breakdown of the operation.

  • Created large string variable to compare
  • Performed operation 10,000,000 times and timed the duration of the iterations
  • Ran procedure 100 times to calculate better average completion time

The more iterations of the entire experiment that you can perform, the closer the results will be to a truer value. Running the entire experiment between 100 and 200 times seems to give out on average the same amount of time.

Results

Even with such large numbers in iterations, the results were still very close and very minute. The following are the results received using both Firefox and Google Chrome.

Performance test: Firefox

Running 10,000,000 iterations per method:

str == ""                          : 37.00 ms
str === ""                         : 38.00 ms
str.length == 0                    : 38.00 ms
!str                               : 46.00 ms
str == null || str.length == 0     : 46.00 ms

That was the best of average results that I received after running the experiment multiple times in Firefox.

Performance test: Chrome

However, I also ran the script using Chrome and the results from that are the following:

Running 10,000,000 iterations per method:

str == ""                          : 32.60 ms
str === ""                         : 33.00 ms
str.length == 0                    : 33.70 ms
!str                               : 34.70 ms
str == null || str.length == 0     : 42.40 ms

As you can see, Chrome did a much better job all around at processing all operations and both browsers followed the same result pattern. That is, the == check was the fastest and the explicit and implicit null checks, both took longer to complete.

These days, thanks to browser improvements and to hardware upgrades, it's pretty difficult to lack in the performance department unless you are processing big data. While the results of this experiment were obvious, in a real world example, you would rarely be performing 10 millions operations 200 times at any one time.

The winner...

After running performance tests and exploring various edge cases, two methods stand out as the most reliable:

Use str === "" when you want a strict and precise check for empty strings only. Use !str when you want a broader check that also covers null, undefined, 0, NaN, and other falsy values.

Here are some final key takeaways:

  • In Chrome, performance differences were negligible across all methods—even with millions of iterations.

  • In Firefox, str === "" performed slightly better than other checks like !str or .length, though the gap was still minimal.

  • Methods relying on .length can throw errors if the variable is null or undefined, so they require additional defensive checks.

  • The !str method is the most concise but may hide bugs if you care about distinguishing between falsy values.

So, while every method has pros and cons, str === "" is the safest and most direct way to check for an empty string, and !str is great for shorthand logic when precision isn't critical.

Was all of this overkill just to answer a simple question? Probably. But now I’ve got a performance-tested answer ready the next time someone asks. Hopefully you do too.

Walter Guevara is a Computer Scientist, software engineer, startup founder and previous mentor for a coding bootcamp. He has been creating software for the past 20 years.
AD: "Heavy scripts slowing down your site? I use Fathom Analytics because it’s lightweight, fast, and doesn’t invade my users privacy." - Get $10 OFF your first invoice.

Community Comments

No comments posted yet

Code Your Own Classic Snake Game – The Right Way

Master the fundamentals of game development and JavaScript with a step-by-step guide that skips the fluff and gets straight to the real code.

Ad Unit

Current Poll

Help us and the community figure out what the latest trends in coding are.

Total Votes:
Q:
Submit

Add a comment