When converting a string to a boolean, what are the advantages of having a programming language evaluate an empty string as true and what are the advantages of having it evaluate it to false?
closed as primarily opinion-based by user40980, gnat, mattnz, GlenH7♦, Kilian Foth Oct 10 '13 at 14:03
Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.
if (str). If an empty string didn't evaluate to false (along with other states like
undefined), you would have to do the following:
if (typeof str !== "undefined" && str != null && str !== "").
This is far more verbose.
An alternate interpretation is that the default state of a primitive evaluates to false. For booleans, this is false. For integers, this is 0. For strings, that would be an empty string. Conceptually, there's no guarantee of nulls existing in a given type system, a value should have a default state.
Converting a string to boolean true or false and other implicit conversions are charterized thusly...
The advantages: possibly more succinct,clever looking code; possibly some more fluidity and expressiveness when writing code quickly; maybe good for quick and loose prototypeing or scripting
are easily outweighted by the
Disadvantages: confusing, lacking portability, reduces maintainability, and verges on intentional obfuscation
Also note that many of these pros and cons also apply to excessive use of operator overloading, which this is a special case of, basically.
Advantages: You save two seconds of coding time having to type less.
Disadvantages: Code is less intention-evident, making you waste the two seconds you saved having to carefully read and mind-evaluate the line of code everytime you come across it.
Consider this pseudo-code:
print "First name: " + firstname if middlename: print "Middle name: " + middlename print "Last name: " + lastname
This and many related cases is where "empty string is false-ish" is useful. Keep in mind that direct evaluation of non-boolean values as boolean is usually restricted to script-ish languages that where build with user interfaces in mind.