ProgrammingJavascriptCareerProductivityGadgetsASP.NETWeb Design

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

Written by
Published on
Modified on
Filed under
What is the best way to check for an empty string in JavaScript

A student recently asked me what the best way to check for an empty string in JavaScript was. I answered in the best way that I knew how and gave various methods that check for empty strings, such as checking for the value and checking the length of the variable. This left me wondering for some time after our conversation how accurate I was with my answer. And while usually code is left to subjectivity many a time, there must be one method that leans more towards the best practice or at least to improved performance.

The following is how I would check for an empty string, pretty much 100% of the time. It's simple and to the point and requires very little thinking on my part. And of course, you always have the option of the === as well, which checks both for type and value.


var str = 'hi';

if (str == '')
{
}

And here is another way to check for an empty string. If the length is zero, then we know that the string is empty of content.


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 = 'hi';

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

}

I wanted to find out which method is best however based on various markers, performance being a key one and usability being the second. And so I created various scripts to really push these functions to their limit and to track the execution time.

Performance tests

The first thing I wanted to check was the performance difference between the 2 methods listed above. In order to do that, I had to essentially 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 averages and such. And this is because an if-else statement by itself isn't at all very resource intensive. To give an example, running a loop with 1 million if-else 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
  • Performed operation 10,000,000 times and timed the duration of the function
  • 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. And the results are not what was expected once again.

Results were achieved using Firefox

[str == ""] - average: 9.94
[str.length == 0] - average: 6.43
[if (str)] - average: 11.33

That was the best of average results that I received after running the experiment multiple times in Firefox. However, I also ran the script using Chrome and the results from that are the following:

Results were achieved using Chrome

[str = ""] - average: 6.213000000061584
[str.length == 0] - average: 6.366999999954714
[if (str)] - average: 6.1740000000281725

As you can see, Chrome did a much better job all around at processing all 3 operations and the average timings all much too close to make any assumptions here. Each operation essentially ran in the same amount of time across the board. This goes go to show how performance with JavaScript is highly dynamic and based on much more than just the syntax that you use.

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.

Using ===

Using the === comparison will check for both the type and the value of the given elements. Given this, will it increase the overall run-time? Running the experiment again with the === gave no significant results and as far as I could tell, did not really change the run-time. Which is definitely good to know, as you won't have to wonder anymore as to whether you should or should not use it.

null values and undefined

Things change a bit however if null values come into play. In JavaScript, null values do not equal to empty strings, and so JavaScript will promptly respond with a friendly false. The run time for that operation is unchanged. If we were to check with the second method of using 'length' however, the function would fail, and rightfully so. If a variable is null, it can't possibly have a property named length.

So we can check for the length of a string to verify if it is empty, but we'll also have to check if the variable is null. Will this increase the overall run time?


var str = '';

if (str == null || str.length == 0)
{

}

This actually has the same running time as before, more or less. When dealing with milliseconds some very minute room for error is present. The only issue above is of course that we have to add an extra check for null values ourselves.

We are just checking for 'null' in the example above. But just as likely, we could run into a case where the variable is 'undefined'. And while we could continue to keeping adding checks for nulls and undefined variables, there is a more concise way in JavaScript.

The following will check against null, 'undefined', '' and false, which seems like the right way to go.


var str = '';

if (!str)
{

}

However, a few things to note using this method. For one, in Firefox it ran with the worst performance, which makes absolute sense since it is including every type of check by default. However, in Chrome there was no discernible difference in performance when compared to the other methods.

And secondly, sometimes we do in fact need to check if a variable is null or 'undefined' for very specific reasons involving our application. An undefined case for example, might signify that something didn't quite go right with this process and exiting might be a good route to take at this point. With the catch-all method above, this would not be possible.

The winner...

Based on everything that I've covered so far, it's pretty difficult to choose any one method as a clear winner. The following are key points to note:

  • As we saw in the small experiment being run above, performance isn't going to be a huge factor in this case, particularly if you are using Chrome as every method has the exact same run time.
  • Checking for the length of a string will require us to not have any 'null' or 'undefined' values, as this will result in an error case.
  • Null checks have no clear performance penalties
  • if (object) checks against every type of unwanted value or type

Every method mentioned has their own set of pros and cons in this case, so the winner really comes down a personal and subjective case. Based on the results of the performance tests however and the overall control that we have when checking, I would select the first method as the winner. Based on the fact that in came 2nd in performance in Firefox and still gives us the ability to separate null checks.

This might have seemed like overkill in trying to figure out how to detect an empty string, and that's because it is. But now I have an answer that makes sense for the most part, just in case anybody asks me again. Hopefully you found this somewhat informative. It is always nice to get good solid data on something that we normally use with little attention paid to it.

Walter Guevara is a software engineer, startup founder and currently teaches programming for a coding bootcamp. He is currently building things that don't yet exist.

Comments

No messages posted yet

Developer Poll

Q:

Stay up to date

Sign up for my FREE newsletter. Get informed of the latest happenings in the programming world.

Add a comment

Keep me up to date on the latest programming news
Add Comment

Stay up to date

Get informed of the latest happenings in the programming world.

No thanks