The following shows that "0"
is false in Javascript:
>>> "0" == false
true
>>> false == "0"
true
So why does the following print "ha"
?
>>> if ("0") console.log("ha")
ha
The following shows that "0"
is false in Javascript:
>>> "0" == false
true
>>> false == "0"
true
So why does the following print "ha"
?
>>> if ("0") console.log("ha")
ha
Your quotes around the
0
make it a string, which is evaluated as true.Remove the quotes and it should work.
coerces x using JavaScript's internal toBoolean (http://es5.github.com/#x9.2)
coerces both sides using internal toNumber coercion (http://es5.github.com/#x9.3) or toPrimitive for objects (http://es5.github.com/#x9.1)
For full details see http://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/
== Equality operator evaluates the arguments after converting them to numbers. So string zero "0" is converted to Number data type and boolean false is converted to Number 0. So
Same applies to `
=== Strict equality check evaluates the arguments with the original data type
Same applies to
In
The String "0" is not comparing with any arguments, and string is a true value until or unless it is compared with any arguments. It is exactly like
But
`
It's PHP where the string
"0"
is falsy (false-when-used-in-boolean-context). In JavaScript, all non-empty strings are truthy.The trick is that
==
against a boolean doesn't evaluate in a boolean context, it converts to number, and in the case of strings that's done by parsing as decimal. So you get Number0
instead of the truthiness booleantrue
.This is a really poor bit of language design and it's one of the reasons we try not to use the unfortunate
==
operator. Use===
instead.The reason is because when you explicitly do
"0" == false
, both sides are being converted to numbers, and then the comparison is performed.When you do:
if ("0") console.log("ha")
, the string value is being tested. Any non-empty string istrue
, while an empty string isfalse
.It's according to spec.
ToBoolean, according to the spec, is
And that table says this about strings:
Now, to explain why
"0" == false
you should read the equality operator, which states it gets its value from the abstract operationGetValue(lref)
matches the same for the right-side.Which describes this relevant part as:
Or in other words, a string has a primitive base, which calls back the internal get method and ends up looking false.
If you want to evaluate things using the GetValue operation use
==
, if you want to evaluate using theToBoolean
, use===
(also known as the "strict" equality operator)