Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use string.length == 0 over string == "" when checking for empty string in ECMAScript?

Most of the developers on my current project use a (to me) strange way to check for empty strings in ECMAScript:

if (theString.length == 0)
    // string is empty

I would normally write this instead:

if (theString == "")
    // string is empty

The latter version seems more readable and natural to me.

Nobody I asked seemed to be able to explain the advantages of version 1. I guess that at some time in the past somebody told everybody that this is the way to do it, but now that person left and nobody remembers why it should be done this way.

I'm wondering whether there is a reason why I should choose the first version over the second? Does it matter, is one version better than the other one? Is one version safer or faster for some reason?

(We actually do this in Siebel eScript which is compliant with ECMAScript Edition 4)

Thanks.

like image 273
Thomas Müller Avatar asked Dec 01 '09 23:12

Thomas Müller


People also ask

Is an empty string length 0?

The Java programming language distinguishes between null and empty strings. An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters.

How do you evaluate an empty string?

Java String isEmpty() Method The isEmpty() method checks whether a string is empty or not. This method returns true if the string is empty (length() is 0), and false if not.

How do you check if a string is blank in JavaScript?

Use the length property to check if a string is empty, e.g. if (str. length === 0) {} . If the string's length is equal to 0 , then it's empty, otherwise it isn't empty.

What Does empty string mean in JavaScript?

The value null represents the absence of any object, while the empty string is an object of type String with zero characters. If you try to compare the two, they are not the same.


2 Answers

I actually prefer that technique in a number of languages, since it's sometimes hard to differentiate between an empty string literal "" and several other strings (" ", '"').

But there's another reason to avoid theString == "" in ECMAScript: 0 == "" evaluates to true, as does false == "" and 0.0 == ""...

...so unless you know that theString is actually a string, you might end up causing problems for yourself by using the weak comparison. Fortunately, you can avoid this with judicious use of the strict equal (===) operator:

if ( theString === "" )
   // string is a string and is empty

See also:

  • What is the best way to check for an empty string in JavaScript?
like image 136
4 revs Avatar answered Sep 22 '22 11:09

4 revs


The problem is that if theString is set to 0 (zero) your 2nd example will evaluate to true.

like image 23
Michael Burr Avatar answered Sep 21 '22 11:09

Michael Burr