Why are some non-empty lines judged to be false in JavaScript?

According to this table in the ECMAScript standard , string values โ€‹โ€‹with a length of 0 should be evaluated as boolean false .

So, are these statements evaluated using true ?

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

All these lines are longer than 0. For example:

Not falsey

Although I understand that "0" evaluates to false because it can be forced to a numeric 0 , I cannot explain why these lines are false. What's happening?

(Obviously, I can use === for rigorous comparisons, but in this case I need a free comparison in my code, however, I did not expect a non-empty string to be considered false.)

+5
source share
1 answer

You are using a free comparison that does type conversion. Whenever you compare Boolean, both values โ€‹โ€‹are actually converted to numbers ( spec, steps 7 and 5 ). false is 0 and (surprisingly!) every line containing only space characters is also converted to 0 (when converted to a number) ( specifications ):

MV StringNumericLiteral ::: StrWhiteSpace - 0 .


I did not expect a non-empty string to be considered false

Comparison A value with a boolean is very different from converting a value to a boolean. "Falsy" means that the value is converted to false when converted to logical. However, again, in your case, the values โ€‹โ€‹are first converted to numbers.

Example:

 Number(" ") // 0 ( == Number(false)) // vs Boolean(" ") // true 
+9
source

Source: https://habr.com/ru/post/1207246/


All Articles