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.
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.
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
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 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
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.
The following will check against null, 'undefined', '' and false, which seems like the right way to go.
var 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.
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.
Thumbs up if you enjoyed this post!
Suggest the next blog post
Walter G. is a software engineer with over 10 years of professional experience. When he isn't blogging or being a CTO he enjoys coding randomly complex things that he hopes many people will get a chance to use one day.