Sarfraz
Sarfraz

Reputation: 382696

JavaScript string resolves to false

Why both of these resolve to false:

console.log("potato" == false); //false
console.log("potato" == true); //false

Because what I know when using == loose comparison, JS coerces the operand. Since in JS, non-empty string should be true, why do above return false above ?

Upvotes: 0

Views: 319

Answers (2)

steveyang
steveyang

Reputation: 9288

There needs a clarification about the == operator. From ECMA-262 Section 11.9.3 the rule6, rule7 and later rule4 determines your result

rule 6. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.

rule 7. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).

rule 4. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).

In your context, false and true will be converted to 0 and 1, while the 'potato' will be converted to NaN, the comparison expression's value is always false.

"potato" == false // => "potato" == 0 => NaN == 0
"potato" == true // => "potato" == 1 => NaN == 1

Similarly, in '' == true comparison, '' will be converted to 0 while true will be converted to 1, the expression is false.

'' == false // => 0 == 0
'' == true // => 0 == 1

Due to the non-intuitive implementation of ==,=== is encouraged to use in comparison.

Upvotes: 5

adis
adis

Reputation: 5951

You mean Truthy and Falsy Values:

if ("potato") {
   console.log("true")
}

But here you compare the String "potato" and a true, JavaScript will try to cast to a comparable thing and that is not the case when you compare the two values you have.

Upvotes: 0

Related Questions