1

Are all non empty strings evaluated to true?

From ECMAScript:

Table 11 - ToBoolean Conversions

Undefined: false
Null: false
Boolean: The result equals the input argument (no conversion).
Number: The result is false if the argument is +0, -0, or NaN; otherwise the result is true.
String: The result is false if the argument is the empty String (its length is zero); otherwise the result is true.
Object: true

the answer should be yes. But then i'm wondering why:

alert(" " == false); 

returns true. {same result with e.g "\t\n\r"}

I don't have any particular use case, I'm just wondering it.

A. Wolff
  • 74,033
  • 9
  • 94
  • 155

2 Answers2

1

It's because JavaScript describes whitespace only strings as having a toNumber conversion to 0.

You can test this using the unary + operator:

console.log(+"\t\n\r"); // 0

Because the == isn't so simple as a toBoolean conversion, you don't get the same result as you would if you did !!"\t\n\r", where the toBoolean conversion considers all non-empty strings to be true.

When the == is used with operands of different types, the algorithm usually coerces the types down until they're both numbers. That's why the toNumber conversion is relevant here.

cookie monster
  • 10,671
  • 4
  • 31
  • 45
  • @A.Wolff: Yes, that's an example of a whitespace-only string. Those are escape sequences that are just part of the literal syntax. The resulting string will only have whitespace. :-) – cookie monster Jan 07 '14 at 18:45
1

A StringNumericLiteral that is empty or contains only white space is converted to +0.

See page 44 in the PDF you linked

Mirco
  • 2,940
  • 5
  • 34
  • 57