Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do some non-empty strings evaluate to "false" in JavaScript?

According to this table in the ECMAScript standard, string values that have length 0 should be evaluated as boolean false.

How come, then, these statements evaluate to true?

"\t" == false
" " == false
"\n" == false
"     " == false

All those strings have a length greater than 0. For example:

Not falsey

While I understand that "0" evaluates to false because it can be coerced to a numeric 0, I can't explain why these strings are falsey. What's going on?

(Obviously I can use === for a strict comparison, but in this case in my code, I need the loose comparison, however I wasn't expecting a non-empty string to be considered falsey.)

like image 779
Matt Avatar asked Nov 19 '14 20:11

Matt


People also ask

Does empty string evaluate to false in JavaScript?

Description. A falsy value is something which evaluates to FALSE, for instance when checking a variable. There are only six falsey values in JavaScript: undefined , null , NaN , 0 , "" (empty string), and false of course.

Does empty string evaluate as false?

Empty strings are "falsy" which means they are considered false in a Boolean context, so you can just use not string.

Does 0 evaluate to false in JavaScript?

In JavaScript “0” is equal to false because “0” is of type string but when it tested for equality the automatic type conversion of JavaScript comes into effect and converts the “0” to its numeric value which is 0 and as we know 0 represents false value. So, “0” equals to false.

What does empty string evaluate to?

Java String isEmpty() method with example Java String isEmpty() method checks whether a String is empty or not. This method returns true if the given string is empty, else it returns false. In other words you can say that this method returns true if the length of the string is 0.


1 Answers

You are using loose comparison, which performs type conversion. Whenever you compare against a Boolean, both values are actually converted to numbers (spec, steps 7 and 5). false is 0 and (surprisingly!)every string containing only white space characters is converted to 0 as well (when converted to a number) (spec):

The MV of StringNumericLiteral ::: StrWhiteSpace is 0.


I wasn't expecting a non-empty string to be considered falsey

Comparing a value against a Boolean is very different from converting a value to a Boolean. "Falsy" means that the value is converted to false when converted to a Boolean. However, again, in your case the values are converted to numbers first.

Example:

Number("    ") // 0 ( == Number(false))
// vs
Boolean("    ") // true
like image 136
Felix Kling Avatar answered Oct 19 '22 09:10

Felix Kling