It probably was asked before but I could't find it. I read the specs too, didn't see anything bizzare that would explain why "0"
evaluates to true
.
So why would "0" ? "yes" : "no"
return yes
?
("0"==true) ? "yes" : "no"
works as expected.
It probably was asked before but I could't find it. I read the specs too, didn't see anything bizzare that would explain why "0"
evaluates to true
.
So why would "0" ? "yes" : "no"
return yes
?
("0"==true) ? "yes" : "no"
works as expected.
Non-empty strings are truthy. "0"
is not 0
.
However, comparison will coerce 0
to a number.
Note, the only string which can be coerced to true
during comparison is "1"
. (Please let me know if there are edge cases I'm missing!)
"true" == true // false
"foo" == true // false
"0" == true // false
"1" == true // true
If a string has atleast one character then the string will evaluate to truthy. As a result your first example will return "yes".
If you had used something like the following however it would have returned no:
"" ? "yes" : "no" // this evaluates to "no" since an empty string is considered falsey
This is a direct result of how type coercion occurs in javascript. I would encourage you to checkout the following link for more information on what type coercion is and how it works: Type Coercion