Is a string of whitespace truthy or falsy in JavaScript?
Is a string of whitespace truthy or falsy?
It's truthy, as others indicated. However, your comparsion
' ' == true
is not checking whether ' '
is truthy. It's comparing two values, which is a different thing and uses specific comparison rules. The JS spec is that any ==
comparison with a boolean first coerces the boolean to a number:
If Type(y) is Boolean, return the result of the comparison
x == ToNumber(y)
.
So your code is equivalent to
' ' == Number(true)
which is the same as
' ' == 1
Next, to compare a string and a number, JS converts the string to a number. Again, quoting the spec:
If Type(x) is String and Type(y) is Number, return the result of the comparison
ToNumber(x) == y
.
So we now have
Number(' ') == 1
Number(' ')
is 0
. The spec says:
The MV of StringNumericLiteral ::: StrWhiteSpace is 0.
So this becomes
0 == 1
which, as you found, is false. See http://ecma262-5.com/ELS5_HTML.htm#Section_11.9.3 for details.
As other answers have explained not being equal (==
) to true
is not the same as being falsy. Falsy is a different concept, which roughly means the value to which an expression is coerced when a boolean is required (such as the condition of an if
statement) is false.
The string ' '
is a "truthy" value.
Here is a list of the "falsy" values:
false
null
undefined
0
NaN
''
You have to understand that "truthy" is not the same thing as true
. A value can be "truthy" without being true
. For example, if we did 5 == true
, we would get false
, even though 5
is a "truthy" value.
In general, pretty much every value is "truthy" (excluding the ones mentioned above). But, the easiest way to check if something is "truthy"/"falsy" is by doing something like this:
var value = valueToTest;
if (value) {
console.log('Truthy!');
} else {
console.log('Falsy!');
}