In JavaScript, why is "0" equal to false, but when tested by 'if' it is not false by itself?

JavascriptBoolean

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

Tables displaying the issue:

truthy if statement

and == truthy comparisons of all object types in javascript

Moral of the story use === strict equality displaying sanity

table generation credit: https://github.com/dorey/JavaScript-Equality-Table

Solution 2 - Javascript

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 is true, while an empty string is false.

> Equal (==) > > If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory. > > (From Comparison Operators in Mozilla Developer Network)

Solution 3 - Javascript

It's according to spec.

12.5 The if Statement
.....

  1. If ToBoolean(GetValue(exprRef)) is true, then a. Return the result of evaluating the first Statement.
  2. Else, ....

ToBoolean, according to the spec, is

> The abstract operation ToBoolean converts its argument to a value of type Boolean according to Table 11:

And that table says this about strings:

enter image description here

> The result is false if the argument is the empty String (its length is zero); otherwise the result is true

Now, to explain why "0" == false you should read the equality operator, which states it gets its value from the abstract operation GetValue(lref) matches the same for the right-side.

Which describes this relevant part as:

if IsPropertyReference(V), then
a. If HasPrimitiveBase(V) is false, then let get be the [[Get]] internal method of base, otherwise let get
be the special [[Get]] internal method defined below.
b. Return the result of calling the get internal method using base as its this value, and passing
GetReferencedName(V) for the argument

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 the ToBoolean, use === (also known as the "strict" equality operator)

Solution 4 - Javascript

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 Number 0 instead of the truthiness boolean true.

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.

Solution 5 - Javascript

// I usually do this:

x = "0" ;

if (!!+x) console.log('I am true');
else      console.log('I am false');

// Essentially converting string to integer and then boolean.

Solution 6 - Javascript

Your quotes around the 0 make it a string, which is evaluated as true.

Remove the quotes and it should work.

if (0) console.log("ha") 

Solution 7 - Javascript

It is all because of the ECMA specs ... "0" == false because of the rules specified here http://ecma262-5.com/ELS5_HTML.htm#Section_11.9.3 ...And if ('0') evaluates to true because of the rules specified here http://ecma262-5.com/ELS5_HTML.htm#Section_12.5

Solution 8 - 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

> "0" == false // true

Same applies to `

> false == "0" //true

=== Strict equality check evaluates the arguments with the original data type

> "0" === false // false, because "0" is a string and false is boolean

Same applies to

> false === "0" // false

In > if("0") console.log("ha");

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

> if(true) console.log("ha");

But

> if (0) console.log("ha"); // empty console line, because 0 is false

`

Solution 9 - Javascript

This is the reason why you should whenever possible use strict equality === or strict inequality !==

"100" == 100

true because this only checks value, not the data type

"100" === 100

false this checks value and data type

Solution 10 - Javascript

The "if" expression tests for truthiness, while the double-equal tests for type-independent equivalency. A string is always truthy, as others here have pointed out. If the double-equal were testing both of its operands for truthiness and then comparing the results, then you'd get the outcome you were intuitively assuming, i.e. ("0" == true) === true. As Doug Crockford says in his excellent JavaScript: the Good Parts, "the rules by which [== coerces the types of its operands] are complicated and unmemorable.... The lack of transitivity is alarming." It suffices to say that one of the operands is type-coerced to match the other, and that "0" ends up being interpreted as a numeric zero, which is in turn equivalent to false when coerced to boolean (or false is equivalent to zero when coerced to a number).

Solution 11 - Javascript

This is because JavaScript uses type coercion in Boolean contexts and your code

if ("0") 

will be coerced to true in boolean contexts.

There are other truthy values in Javascript which will be coerced to true in boolean contexts, and thus execute the if block are:-

if (true)
if ({})
if ([])
if (42)
if ("0")
if ("false")
if (new Date())
if (-42)
if (12n)
if (3.14)
if (-3.14)
if (Infinity)
if (-Infinity)

Solution 12 - Javascript

if (x) 

coerces x using JavaScript's internal toBoolean (http://es5.github.com/#x9.2)

x == false

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/

Solution 13 - Javascript

I have same issue, I found a working solution as below:

The reason is

    if (0) means false, if (-1, or any other number than 0) means true. following value are not truthy, null, undefined, 0, ""empty string, false, NaN

never use number type like id as

      if (id) {}

for id type with possible value 0, we can not use if (id) {}, because if (0) will means false, invalid, which we want it means valid as true id number.

So for id type, we must use following:

   if ((Id !== undefined) && (Id !== null) && (Id !== "")){
                                                                                
                                                                            } else {

                                                                            }
                                                                            

for other string type, we can use if (string) {}, because null, undefined, empty string all will evaluate at false, which is correct.

       if (string_type_variable) { }

Solution 14 - Javascript

In JS "==" sign does not check the type of variable. Therefore, "0" = 0 = false (in JS 0 = false) and will return true in this case, but if you use "===" the result will be false.

When you use "if", it will be "false" in the following case:

[0, false, '', null, undefined, NaN] // null = undefined, 0 = false

So

if("0") = if( ("0" !== 0) && ("0" !== false) && ("0" !== "") && ("0" !== null) && ("0" !== undefined) && ("0" !== NaN) )
        = if(true && true && true && true && true && true)
        = if(true)

Solution 15 - Javascript

I came here from search looking for a solution to evaluating "0" as a boolean. The technicalities are explained above so I won't go into it but I found a quick type cast solves it.

So if anyone else like me is looking to evaluate a string 1 or 0 as boolean much like PHP. Then you could do some of the above or you could use parseInt() like:

x = "0";
if(parseInt(x))
//false

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnonopolarityView Question on Stackoverflow
Solution 1 - JavascriptJoeView Answer on Stackoverflow
Solution 2 - JavascriptjdiView Answer on Stackoverflow
Solution 3 - JavascriptIncognitoView Answer on Stackoverflow
Solution 4 - JavascriptbobinceView Answer on Stackoverflow
Solution 5 - JavascriptThavaView Answer on Stackoverflow
Solution 6 - JavascriptJason GennaroView Answer on Stackoverflow
Solution 7 - JavascriptNarendra YadalaView Answer on Stackoverflow
Solution 8 - JavascriptVishnu K. PanickerView Answer on Stackoverflow
Solution 9 - JavascriptDmitriy MalayevView Answer on Stackoverflow
Solution 10 - JavascriptJollymorphicView Answer on Stackoverflow
Solution 11 - JavascriptSachinView Answer on Stackoverflow
Solution 12 - JavascriptAngusCView Answer on Stackoverflow
Solution 13 - JavascripthoogwView Answer on Stackoverflow
Solution 14 - JavascriptvtcView Answer on Stackoverflow
Solution 15 - JavascriptAbu NoohView Answer on Stackoverflow