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 MichaelT, gnat, mattnz, GlenH7, Kilian Foth Oct 10 '13 at 14:03Many 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. |
|||||||||||||||||||||
|
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. |
|||||||||||||||||||||
|
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 Because Hiding complexity behind built-in 'tricks' of each language is clever at first and devastating later. if the subject is complex, like str can be undefined type, str can be null, str can be defined, not null, but blank, YOU the programmer must be explicit how you want deal with this. at the point of usage. not buried in some docs on the JavaScript API 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. |
|||
|
In the context of JavaScript (I'm guessing this is what generated the question), an empty string evalutes to false in a boolean context because it allows you to use the pattern 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. |
|||||
|
Consider this pseudo-code:
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. |
|||||||||||||
|